简体   繁体   中英

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.

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.

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