Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory usage and speed of objects vs arrays in javascript

What will use more memory, items1 where each item is an array or items2 where each item is an object:

var items1=[['James Bond',8,40],
...,
['Superman',9999,36]];
var items2=[{Name,'James Bond',strength:8,coolness:40},
...,
{Name,'Superman',strength:9999,coolness:36}];

Which will be the fastes way to fetch data search1 or search2?

var search1=items[432][2];
var search2=items2[432]["coolness"];

PS: The given scores are unofficial and my personal opinion of the 2 characters

SECOND EDIT: I had a picture of a test but it was scewed as pointed out by Felix. This is more correct: http://jsperf.com/sparse-objects/3 which says array lookup is 20 % faster.

like image 572
Rune Jeppesen Avatar asked Jan 16 '13 10:01

Rune Jeppesen


1 Answers

I am not the best at writing unit tests, but here's a simple example that tells me that there's not too much of a difference:

// see code in fiddle

http://jsfiddle.net/ryanwheale/HbHxv`

And here is another with a little more output and control:

// see code in fiddle

http://jsfiddle.net/ryanwheale/HbHxv/4/

I like the 2nd option because you can see how much memory each method takes by using Chrome's Timeline in the dev tools. Start recording, and click the "objects" button several times, wait a few seconds and then click the "arrays" button several times. You will see the memory consumed by objects is more than the memory used by Arrays. There also seems to be a slight favor for arrays in terms of time of execution. However, we are talking about a million items... which is highly unrealistic.

like image 60
Ryan Wheale Avatar answered Oct 11 '22 09:10

Ryan Wheale