问题
Right now I have the following javascript dictionary
var a = {};
a['SVG343'] = 1942;
a['UAL534'] = 2153;
Those numbers on the right represent times, and the keys are unique ids. I wanted to make the ids the keys since they are unique. My problem is given a time find the corresponding id. How was I going to do this was go through each entry in the dictionary until I find the correct time and use the current key to get the id.
However I'm worried about performance, my question is, does going through each entry in the dictionary (O(n)) significantly slower than any other method?
回答1:
You could build an index from the times:
var indexByTimes = {};
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
indexByTimes[a[prop]] = prop;
}
}
And for multiple time values, use an array for the IDs:
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
if (indexByTimes.hasOwnProperty(a[prop])) {
indexByTimes[a[prop]].push(prop);
} else {
indexByTimes[a[prop]] = [prop];
}
}
}
Then you can access all IDs corresponding to the time 1942 with indexByTimes['1942']
in O(1).
回答2:
Iterating through all the keys of a dictionary is O(n)
. So also iterating through a.items()
is also going to be O(n)
. But iterating through all keys and then looking up the value (i.e. for(var key in a) { x += a[key]; }
) is O(n*log(n)
). So it would be preferable to either iterate though a.items()
or just use a list
来源:https://stackoverflow.com/questions/4564160/javascript-dictionary-performance-question