问题
I am using a JavaScript object as a dictionary, and wanted to make keys case-insensitive. I used Object.defineProperty()
to implement this:
Object.defineProperty(Object.prototype, "getKeyUpperCase", {
value: function(prop) {
for (var key in this) {
if (key.toUpperCase() === prop.toUpperCase()) {
return this[key];
};
};
},
enumerable: false
});
What is the time complexity of searching an object via key in JavaScript? I'm expecting the dictionary to hold around 1 million keys.
To me it looks like worst case would be O(n)
, best case would be O(1)
and average case would be O(n/2)
. Is this correct?
Would it be substantially more efficient to retrieve the object's keys as an array (Object.Keys(dictionary).map(function(key) return key.toUpperCase()).sort()
) to check if the key exists? Am I correct in saying that the average time complexity of this operation is O(log n)
?
Usage of the dictionary is along the lines of this:
var dictionary = {/* some million keys or so */};
var oldKey = someSmallArray[i];
var newValue = dictionary.getKeyUpperCase(oldKey.trim().toUpperCase());
回答1:
First, some thought about big-O notation:
This mathematical tool tries to grab the concept of "order of magnitude" in a long-term scenario. As size grows constants get less and less importance. Hence calculating big-O usually we don't bother with constants.
That's why O(n/2) = O(n).
So the linear lookup has O(n) time complexity.
About the sorting:
The sort algorithm of JavaScript is browser dependent but you can assume an O(n log n) complexity for that. Usually, it doesn't worth to sort for only one lookup but if you can sort only once and you can make several lookups maybe it is worth it. By the way, If you have a sorted list to search maybe you could try to implement binary search to speed up your searching.
来源:https://stackoverflow.com/questions/46391041/what-is-the-time-complexity-of-searching-javascript-object-keys