Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I increase lookup speed by positioning properties in object?

I've seen a lot of questions about the fastest way to access object properties (like using . vs []), but can't seem to find whether it's faster to retrieve object properties that are declared higher than others in object literal syntax.

I'm working with an object that could contain up to 40,000 properties, each of which is an Array of length 2. I'm using it as a lookup by value.

I know that maybe 5% of the properties will be the ones I need to retrieve most often. Is either of the following worth doing for increased performance (decreased lookup time)?

  1. Set the most commonly needed properties at the top of the object literal syntax?
  2. If #1 has no effect, should I create two separate objects, one with the most common 5% of properties, search that one first, then if the property isn't found there, then look through the object with all the less-common properties?

Or, is there a better way?

like image 453
MDe Avatar asked Feb 03 '14 21:02

MDe


2 Answers

I did a js perf here: http://jsperf.com/object-lookup-perf

I basically injected 40000 props with random keys into an object, saved the "first" and "last" keys and looked them up in different tests. I was surprised by the result, because accessing the first was 35% slower than accessing the last entry.

Also, having an object of 5 or 40000 entries didn’t make any noticeable difference.

The test case can most likely be improved and I probably missed something, but there is a start for you.

Note: I only tested chrome

like image 161
David Hellsing Avatar answered Sep 22 '22 13:09

David Hellsing


Yes, something like "indexOf" searches front to back, so placing common items higher in the list will return them faster. Most "basic" search algorithms are basic top down (simple sort) searches. At least for arrays.

like image 37
Organiccat Avatar answered Sep 18 '22 13:09

Organiccat