HeroWarsHelper

Automation of actions for the game Hero Wars

< Spätná väzba na HeroWarsHelper

Otázka/komentár

§
Pridaný: 31.07.2026

Speed up the Battle Calculation by 50%:

Instead of:

for (let titanId in beforeTitans) {
   const titan = beforeTitans[titanId];

You do:

for (let titan of Object.values(beforeTitans)) {

Same for the AfterSum and that in all 2 getState functions. This function is called thousand of times in a second and always iterates over ALL Property Keys of an Object, 2 times, each call.. You will feel the Speed up.

The reason is, that for ... in is complicated... for example 'toString' in {} returns true and the reason is, that every Object has an toString function. For an Object it will return most likely [Object object] for example. You can also just skip all not needed values by just doing an isOwnProperty check, but why iterating them in the first place if you don't have to. Replace it with Object.values or with let [id, value] of Object.entries(beforeTitans) and never use for ... in in JavaScript in the future please.

ZingerYAutor
§
Pridaný: 01.09.2026
Upravený: 01.09.2026

Perhaps I didn't quite understand what you were suggesting, but your solution isn't faster than the one used in the script.
Here's the benchmark:

const obj = {};
for (let i = 0; i < 5; i++) {
	obj[4020 + i] = { hp: 10000000 + i * 1000000 };
}

// Test 1: for...in
const start1 = performance.now();
for (let iter = 0; iter < 200000; iter++) {
	let sum = 0;
	for (let key in obj) {
		sum += obj[key].hp;
	}
}
const time1 = performance.now() - start1;

// Test 2: Object.values()
const start2 = performance.now();
for (let iter = 0; iter < 200000; iter++) {
	let sum = 0;
	for (let val of Object.values(obj)) {
		sum += val.hp;
	}
}
const time2 = performance.now() - start2;

console.log(`for...in:        ${time1.toFixed(2)}ms`);
console.log(`Object.values(): ${time2.toFixed(2)}ms`);

My result:
for...in: 26.50ms
Object.values(): 27.10ms

Even if it were twice as fast, it still wouldn't be significantly faster because this feature isn't actually used as often as you wrote.
But some things could definitely be improved, so thanks for your feedback.

Pridať odpoveď

Aby ste mohli pridať odpoveď, prihláste sa.