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]];
}