Reputation: 10924
This question is inspired from competing answers on this question: indexOf with multiple arguments
The user wanted to know an efficient way to test an array for the existence of one or more integers given in an array. Specifically, given an array and the numbers 123
, 124
, and 125
, how can you tell if one or more of these integers exists in the given array. Two solutions were suggested:
Using indexOf()
:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var exists = array.indexOf(123) !== -1 || array.indexOf(124) !== -1 || array.indexOf(125) !== -1;
Or, using some()
:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var exists = array.some(function(item) {
return item === 123 || item === 124 || item === 125;
});
Both the ECMA-262 algorithms for indexOf()
and some()
short-circuit when finding a successful match, but I would have thought that the some()
implementation would be faster when there are no matches. However, another user pointed out that the indexOf()
solution is faster.
How is the indexOf()
code more efficient even though it must iterate over the array more times?
Upvotes: 5
Views: 3673
Reputation: 255155
The thing is - your question is highly relies not on the standard itself, but on how the standard is implemented.
Said that, the results may be not consistent between different engines.
The very obvious assumption that "there is an overhead to call a function" some time in some engine might be mitigated by inlining a function call and some other tricky optimisations.
To summarise: there is no single right answer to that, and any answer that would not use any references to the ES implementations + runtime details (cpu instructions/opcodes, optimisations used) - is simply a speculation.
Upvotes: 7