1

I'm building an Entity System for a game, and basically I'm not sure whether I should use simple objects (dictionaries) or arrays to to store the entities/components by their id.

My biggest issue is that I didn't want a dynamic entity id. If the id was just a string (using the dictionary to store entities), then it would always be valid and I could use storage[id] to get to that entity.

If I used arrays, I thought, the id's of entities, which would represent an index in the storage array, would change. Consider this array of entities:

[
    Entity,
    Entity, //This one is being removed.
    Entity
];

If I was to remove the second entity in that array, I thought that the id required to access the third array would have to change to the id (index) of the (now removed) second entity. That's because I thought about deleting in terms of splice()ing.

But, I could use the delete expression to turn the element (an entity) into an undefined! And, if it's true that arrays in Javascript are actually just objects, and objects logically have infinitely many undefined values, does that mean that undefined values inside arrays don't use up memory?

Initially, I though that arrays were implemented in a way that they were aligned in memory, and that an index was just an offset from the first element, and by this logic I thought that undefined values would use at least the memory of a pointer (because I, actually, thought that pointers to elements are aligned, not elements themselves).

So, if I stored 10k+ entities in this array, and deleteed half of them, would the 5k undefined's use any memory at all?

Also, when I do a for entity in array loop, would these undefined elements be passed?

Also, where can I find resources to see how arrays are actually supposed to be implemented in Javascript? All I can find are general explanations of arrays and tutorials on how to use them, but I want to find out all about these little quirks that can prove important in certain situations. Something like a "Javascript quirks" site would be great.

corazza
  • 31,222
  • 37
  • 115
  • 186

1 Answers1

2

Arrays are not just objects. In particular the length property is very magic.

Of course, a JavaScript engine is allowed to represent the array internally in any way it chooses, as long as the external API remains the same. For instance, if you set randomly separated values then they may be stored as a hash, but if you set consecutive values then they may be optimised into an array.

for ... in does not enumerate properties that are not set. This includes an array literal that skips values e.g. [true, , false], which will only enumerate indices 0 and 2.

Neil
  • 54,642
  • 8
  • 60
  • 72
  • 1
    It's a special property, yes, but it's not magical, as in its semantics are fully specified and known. It's magical for non-programmers for sure, but that's not us `:)` – Šime Vidas Jul 21 '12 at 22:36