Summary: Arrays are a lot smaller than objects, but only slightly faster on newer browsers.
I’m writing an in-memory Javascript app that handles several thousand rows. Each row could be stored either as an array [1,2,3] or an object {"x":1,"y":2,"z":3}. Having read up on the performance of arrays vs objects, I thought I’d do a few tests on storing numbers from 0 to 1 million. The results for Chrome are below. (Firefox 7 was similar.)
| Time | Size (MB) | |
Array: x[i] = i | 2.44s | 8 |
Object: x[i] = i | 3.02s | 57 |
Object: x["a_long_dummy_testing_string"+i]=i | 4.21s | 238 |
The key lessons for me were:
- Browsers used to process arrays MUCH faster than objects. This gap has now shrunk.
- However, arrays are still better: not for their speed, but for their space efficiency.
- If you’re processing a million rows or less, don’t worry about memory. If you’re storing stuff as arrays, you can store 128 columns in 1GB of RAM (1024/8=128).
Comments
Person.Nameis equivalent toPerson['Name']But in the case of Array’s some magic is applied leading to optimisations in storage. Hence I suppose rather than storing unicode strings for “0”, “1” etc., they are stored as integers. Javascript, like English, is berry phunny language :)