Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array index fundamentals

I am not sure how the Javascript engines (specifically browser engines) store an array.

For example - how much memory would this use?

var x = new Array(0, 1, 2, 1000, 100000000);

I want to map integer dates as array indexes, but I need to be sure it isn't a bad idea.

like image 486
Antony Carthy Avatar asked Aug 30 '11 13:08

Antony Carthy


1 Answers

Arrays are "special" in only a couple ways:

  • They've got some interesting array-like methods from their prototype ("slice()" etc)
  • They've got a "magic" length property that tracks the largest numeric property "name"

If you store something at position 10299123 in a brand-new array, the runtime does not use up all your memory allocating an actual, empty array. Instead, it stores whatever you want to store and makes sure that length is updated to 10299124.

Now the problem specifically with dates, if you're talking about storing the timestamp, is that (I think) they're bigger than 32-bit integers. Array indexes are limited to that size. However, all that means is that length won't be correct. If you don't really care about any of the array stuff anyway, then really all you need is a plain object:

var dateStorage = {};

dateStorage[someDate.getTime()] = "whatever";

JavaScript objects can be used as name-value maps as long as the name can be represented as a string (which is clearly true for numbers).

like image 188
Pointy Avatar answered Nov 11 '22 15:11

Pointy