For my application I need a collection that can do fast iteration and fast lookups by key.
Example Data
var data = [
{ myId: 4324, val: "foo"},
{ myId: 6280, val: "bar"},
{ myId: 7569, val: "baz"},
... x 100,000
];
The key is contained within the objects that I want to store. I hacked together Harray (Hash Array) https://gist.github.com/3451147.
Here’s how you use it
// initialize with the key property name
var coll = new Harray("myId");
// populate with data
data.forEach(function(item){ coll.add(item); });
// key lookup
coll.h[4324] // => { myId: 4324, val: "foo"}
// array functionality
coll[1] // => { myId: 6280, val: "bar"}
coll.map(function(item){ return item.val; }); // => ["foo", "bar", "baz"]
coll.length // => 3
// remove value
coll.remove(coll[0]); // delete => { myId: 4324, val: "foo"}
// by key
coll.removeKey(7569) // delete => { myId: 7569, val: "baz"}
// by index
coll.removeAt(0); // delete => { myId: 6280, val: "bar"}
Removal speed seems to be the only tradeoff I can see. The stored objects are shared between the h Object and the Array so I’m not storing 2 copies of anything.
Question
- Should I just stick with using
for into iterate through object properties? - Keep an array of the object’s keys instead of the objects themselves?
- other options?
Note: browser compatibility is not a factor. This is exclusively for chrome.
In order to know if a specific collection can be helpful, you must :
first verify there is a performance problem. If it’s fast enough, don’t worry. To check this, supposing the whole page is slow, use a profiler like the Chrome profiler to check the problem is in the collection you’re currently using
then check the alternate collection you’re building is really faster. To do this a common solution is to benchmark both solutions with a big enough data set using a site like http://jsperf.com/ (or simply by building your own timed tests).
Only after that should you work on ensuring your solution is API-complete, totally bug free, (using test units) and so on.
Doing the two checks I mentioned first might prevent useless work as the standard objects in the V8 engine are amazingly fast and smart.