daintycode daintycode - 1 year ago 72
Javascript Question

large array of numbers vs smaller array of objects

What would be faster when it comes to iterating over all the elements?

Method 1:

let array = [10, 0, 0, 20, 1, 0, 12, 2, 0];

for(let i = 0, l = array.length; i < l; i += 3) {
doSomething(array[i], array[i + 1], array[i + 2]);


Method 2:

let array = [{id:10, x:0, y:0}, {id:20, x:1, y:0}, {id:12, x:2, y:0}];

for(let i = 0, l = array.length, current = null; i < l; ++i) {
current = array[i];
doSomething(current.id, current.x, current.y);
// i'm aware that we could make doSomething work with the object
// -> even a thing to consider?

My guess is that we're faster with 1, but you guys may have more intel of v8, spidermonkey and all that so maybe the object handling and the smaller array would be faster in the end?

Answer Source

Both are O(n). Nothing else matters. Even their memory consumption will only differ minimally. You can do a benchmark yourself when you think that this is performance-critical, but it most likely isn't.

Use objects because they provide a clear structure for your data and make your code more readable. Yes, you should consider passing such an object to doSomething.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download