5

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.

1 Answer 1

11

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I would enjoy a response with more technicalities about Array storage in JS. Unix timestamps are 32 bit integers.
The topic of JavaScript numeric types is very weird and complicated. The ECMA standard document is long and tedious, but it does have pretty clear (if exhaustively detailed) descriptions of language semantics. The Array descriptions in particular are, to me, pretty straightforward.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.