When comparing a JavaScript Array
to an Object
, the distinction may not seem significant. Essentially, an Array
primarily introduces the length
attribute, allowing both Array
s and Object
s to function as numeric arrays:
var ar = new Array();
ar[0] = "foo";
ar["bar"] = "foo";
var ob = new Object();
ob[0] = "foo";
ob["bar"] = "foo";
assert(ar[0] == ob[0] == ar["0"] == ob["0"] == ar.bar == ob.bar); // Should be true.
So the question arises, how is this functionality handled in popular JavaScript engines (V8, JavaScriptCore, SpiderMonkey, etc.)? It is undesirable for arrays to be stored as hash maps with key values. How can we ensure that our data is indeed stored as a genuine array?
Several approaches could potentially be taken by these engines:
Array
is essentially treated as an associative array with string keys, much likeObject
.Array
could have a specialized implementation with a numeric key-backed structure resemblingstd::vector
, along with a density heuristic to manage memory usage when handling very large indices.Array
might share similarities withObject
, but objects could undergo a heuristic process to determine if utilizing an array would be more efficient.- A highly complex method that has not been considered yet.
Having a dedicated array type (like WebGL typed arrays) would streamline this process.