Yes, indexOf is O(n), hence why I called mine a "map" and not a "hash". But if all your keys are strings, Ben's version is faster in almost all cases with lots of keys (though slower for small collections), but still nowhere as fast as native js lookup because of line caches in the engine's JIT. Also all three alternatives have unique capabilities. If you want to store a non-string as a key you have to use a map.
Isn't computer science fun! http://jsperf.com/homegrown-map-hash-vs-native On Sat, Sep 21, 2013 at 1:39 PM, Jorge Chamorro <[email protected]>wrote: > On 21/09/2013, at 19:43, Ben Noordhuis wrote: > > On Sat, Sep 21, 2013 at 6:09 PM, Tim Caswell <[email protected]> wrote: > >> > >> > >> function map() { > >> var keys = []; > >> var values = []; > >> return { get: get, set: set }; > >> function get(key) { > >> return values[keys.indexOf(key)]; > >> } > >> function set(key, value) { > >> var index = keys.indexOf(key); > >> if (index < 0) { > >> index = keys.length; > >> keys[index] = key; > >> } > >> return values[index] = value; > >> } > >> } > > > > That's O(n) lookup time though - rather worse than the O(log n) or > > O(1) characteristics of a JS dictionary. > > Yes, those `.indexOf(key)` can be a pain in the ass. > > -- > ( Jorge )(); > > -- > -- > 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 [email protected] > To unsubscribe from this group, send email to > [email protected] > For more options, visit this group at > http://groups.google.com/group/nodejs?hl=en?hl=en > > --- > You received this message because you are subscribed to the Google Groups > "nodejs" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > For more options, visit https://groups.google.com/groups/opt_out. > -- -- 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 [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/nodejs?hl=en?hl=en --- You received this message because you are subscribed to the Google Groups "nodejs" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. For more options, visit https://groups.google.com/groups/opt_out.
