Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do numeric keys in javascript always sort to the beginning?

So let's say I have something like the following in javascript:

object = {"one": 1, "two": 2, "three": 3, "123": 123};

When I iterate through this, it turns out that the "123" member has jumped to the front of the list, while the order of the others is maintained. If I do something like the following though,

object = {"one": 1, "two": 2, "three": 3, "123 STRING": 123};

the order is maintained. So it seems like a purely numeric key is bumped up, but a key containing non-numeric characters is not. Anyone know why?

like image 379
user1630830 Avatar asked Oct 04 '22 07:10

user1630830


1 Answers

In V8 the data-structures behind an object vary a lot:

  • In-object named properties, stored directly "on the C struct"
  • Out-of-object named properties, stored in an array external to the object, additional indirection
  • Indexed properties (properties whose property names can be turned into integers), stored in an array external to the object but the array index acts as the key
  • Ordered hash table

Named properties are in insertion order because that's most natural with the hidden class evolution/transitions.

Indexed properties are in their actual value order because it would be a waste of memory to store the insertion order.

If you are backed by a hash table, the hash table deliberately fakes the same order that results from the natural optimizations.

It is the same in other browsers too because storing indexed properties, when the numbers are small, in an actual "C array" is a huge optimization. What can vary is whether indexed properties are listed first or named properties.

The spec made this optimization possible by not defining iteration order and V8 was first (at least according to that bug thread) to exploit it.

Indexed keys being listed before named and vice versa is of course arbitrary and doesn't affect any optimizations.

like image 117
Esailija Avatar answered Oct 07 '22 20:10

Esailija