user7119460 user7119460 - 1 month ago 6
Javascript Question

Few large arrays, or one large array of few variables?

apologies if this question has been asked before but I'm finding it hard to word the question in a way that might have been asked before.

Q: Is it more efficient to have something like:


mass[128] = {0.0}
speed[128] = {0.0}
age[128] = {0}


Or:

properties[128] = {mass=0.0, speed=0.0, age=0}


And why? Is there a simple rule to always bear in mind, (are few larger arrays better than many small etc)?

I'm writing in JS using Chrome. Reading and writing to elements very often.

Thanks very much!

Answer

In general, the answer here is: Do what makes the most sense to let you write the simplest, clearest code; and worry about any performance or memory issue if you actually run into one.

Using an array of objects with named properties will likely be more efficient in terms of access time on a modern JavaScript engine, and will likely be less efficient in terms of memory use. In both cases, the difference will be incredibly minor and probably imperceptible.

If your values are numbers and your arrays can be of fixed size, you might use typed arrays, since they really are arrays (where as normal arrays aren't1 unless the JavaScript engine can do it as an optimization). But there are downsides to typed arrays (their being fixed size, for instance), so again, if and when it becomes necessary...

Example of an array of objects with named properties:

var properties = [
    {mass: 0, speed: 0, age: 0},
    {mass: 1, speed: 1, age: 1},
    // ...
];

If you're using ES2015 (you said you're using Chrome, so you can), you might make that a const:

const properties = [
    {mass: 0, speed: 0, age: 0},
    {mass: 1, speed: 1, age: 1},
    // ...
];

That only makes properties a constant, not the contents of the array it points to, so you can still add, remove, or amend entries as desired.


1 That's a post on my anemic little blog.

Comments