On Thu, 17 Mar 2011 23:22:46 +0100, Diego Perini <[email protected]>
wrote:
On Thu, Mar 17, 2011 at 3:01 AM, RobG <[email protected]> wrote:
// Add some properties in order
obj['0'] = 0;
obj.first = 'first';
obj.second = 'second';
obj.third = 'third';
obj.fourth = 'fourth';
obj['5'] = 5;
Chrome 10 and Opera 11 return them in the following order:
0,5,first,second,third,fourth
IE 9 too, IIRC.
Do they get performances benefits on the lookups by reordering members
this way ?
Yes and no.
The performance benefit comes from having number-indexed properties (i.e.,
array
indices) kept separate from the remaining properties. It allows efficient
code
that doesn't convert numbers to strings first, and it makes it easier to
have a
dense array implemented as an underlying flat sequence (and sparse arrays
as
dictionaries/hash-maps).
This implementation means that for the flat fast array, they don't store
the
order of assignment, which would be wasteful in most cases anyway. So when
someone
tries to iterate properties, they don't even know the insertion order of
the
array elements. That's why they are output first.
Other browsers already did the same for arrays, the "new thing" is that
Chrome, Opera
and IE now does the same for non-array objects as for arrays, most likely
to avoid
having to distinguish arrays from non-arrays in the underlying code.
Remember that special cases cost, even if you don't use them, because you
still have
to test for them. Now that every property read can hit a getter that can
throw
an exception, you have to be able to handle exceptions where you didn't
before, even
if it never happens.
Anyway, fixing on *this* particular order, instead of having it be
completely unordered,
still carries some overhead. If the array is sparse and backed by a
dictionary, you
will need to sort the indices to make them in numerical order.
Also outputting non-array indices in insertion order requires you to 1)
retain that
order in the object (an up to 50% increase in size for objects when backed
by a
hash-map) and sort the properties to output them in the correct order.
The fastest thing would definitely be to not have any predictable order,
just as
the JavaScript and ECMAScript specification allows. That won't happen
because people
have begun relying on the order of the existing browsers, so that any new
browser
must try to match that or break existing pages.
/L
--
Lasse Reichstein - [email protected]
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]