ECMAScript currently does not define an order in which keys will be read, 
however it allows implementations to do so, if they keep the 
order consistent. V8 guarantees that non-numeric keys (due to Array's 
behavior) will be read in insertion order, and future drafts of ECMAScript 
may guarantee similar behavior.

Note that JSON and BSON, used by MongoDB, does not provide this guarantee. 
MongoDB can and does re-order keys (usually in alphabetical order).

In any case where you need to iterate over values in a particular order, I 
would use an Array. It is by far more efficient: for..in has to build a 
list of keys before it can iterate over them, and must do so every time you 
iterate over them. If you also need to randomly access objects by a name, 
then you can populate an index in memory as you first iterate over the 
Array.

Interestingly, the only time I've ever depended on key-insertion order is 
in MongoDB, despite the explicit conditions in which it will re-order your 
keys. Heh. All the other times, it's just been more efficient to use an 
Array, and it produces more readable code.

Austin Wright.

On Thursday, August 9, 2012 5:13:07 PM UTC-7, Alan Gutierrez wrote:
>
> Have you ever written Node.js code that counts on the implementation 
> specific 
> Object behavior that mantains the insertion order of properties? 
>
> It could be useful in configuration, for example, to specify fallbacks if 
> the 
> first choice isn't available. 
>
>     var conf = { database: { pg: "psql://localhost/database" 
>                            , mysql: "mysql://localhost/database" } }; 
>
>     for (var type in conf.database) { 
>       try { 
>         useDatabase(require(type), conf.database[type]); 
>       } catch (e) { 
>         if (e.code != 'MODULE_NOT_FOUND') throw e;   
>       } 
>     } 
>
> Great idea or *Greatest* idea? 
>
> Possibly related: 
> http://code.google.com/p/v8/issueObjects/detail?id=164<http://code.google.com/p/v8/issues/detail?id=164>
>  
>
> -- 
> Alan Gutierrez - http://twitter.com/bigeasy - http://github.com/bigeasy 
>

-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nodejs@googlegroups.com
To unsubscribe from this group, send email to
nodejs+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Reply via email to