I have seen in an answer that the Set.has()
method is O(1) and Array.indexOf()
is O(n).
var a = [1, 2, 3, 4, 5];
a.indexOf(5);
s = new Set(a);
s.has(5); //Is this O(1)?
Is Set.has()
really O(1) ?
I have seen in an answer that the Set.has()
method is O(1) and Array.indexOf()
is O(n).
var a = [1, 2, 3, 4, 5];
a.indexOf(5);
s = new Set(a);
s.has(5); //Is this O(1)?
Is Set.has()
really O(1) ?
I don't think the array that has 5 elements is good case to check time complexity.
So based on @Shidersz's snippet, I made a new one that has many elements and invoked once.
Yes. Time complexity of Set.has() is O(1) according to result of the test below.
If one read the specification of
has()
, there is an algorithm describing it:Algorithm for
Set.prototype.has(value)
:The following steps are taken:
And apparently, based on that algorithm and the presence of the word
REPEAT
one can have some confusion about it to beO(1)
(we could think it could beO(n)
). However, on the specification we can read that:Thanks to @CertainPerformance for pointing this.
So, we can create a test to compare
Array.indexOf()
andSet.has()
in the worst case, i.e. look for an item that isn't in the array at all (thanks to @aquinas for pointing this test):And now we can see that
Set.has()
performs better thanArray.indexOf()
. There is also an extra comparison toObject.hasOwnProperty()
to take as reference.Conclusion:
While
O(1)
complexity isn't guaranteed, the specification requires the method to run in sublinear time. AndSet.has()
, generally, will perform better thanArray.indexOf()
.Another Test:
On next example, we going to generate a random set of sample data and use it later to compare the differents methods.
Finally I want to apologize for the confusion the first version of my answer could cause. Thanks to all for giving me a better understanding of my mistakes.