简体   繁体   中英

Is using a numeric for loop with an array of keys faster than iterating over an object with a for-in loop in JavaScript?

Please note: This question is purely hypothetical and for learning purposes. I do not plan on making unnecessary micro-optimizations.

From research that I've done, it seems that using for-in loops are relatively slow compared to other loops. For example, this loop:

const obj = { a: 'a', b: 'b', c: 'c', ... };

for (key in obj) {
  const val = obj[key];
}

is approximately 7 times slower on average than this loop:

const arr = [ 'a', 'b', 'c', ... ];

for (let i = 0; i < arr.length; i++) {
  const val = arr[i];
}

My alternate solution to using for-in is to make an array of keys that I can iterate over with a numeric for loop, then look up those keys in the object.

I'm wondering, would this be a better solution (purely in terms of raw performance) than the for-in loop:

const keys = [ 'a', 'b', 'c', ... ]
const obj = { a: 'a', b: 'b', c: 'c', ... }

for (let i = 0; i < keys.length; i++) {
  const val = obj[keys[i]];
}

Thanks to VLAZ's wonderful support I was able to figure it out after asking elsewhere. The other individual recommended Benchmark.js to me and I concluded that the numeric for w/ lookup keys is roughly 10 times faster than for-in for large data.

Data size:

const iterations = 1000000;

const obj = {};
for (let i = 0; i < iterations; i++) {
  obj1['s' + i] = 1;
}

const arr = [];
for (let i = 0; i < iterations; i++) {
  arr[i] = 's' + i;
}

for-in benchmark:

for (key in obj) {
  const v = obj[key];
}

Completed in: ~0.3174 seconds

numeric for w/ lookup:

for (let i = 0; i < arr.length; i++) {
  const v = obj[arr[i]];
}

Completed in: ~0.0396 seconds

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM