How can Array.indexOf be more efficient than Array.some
Asked Answered
M

1

5

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?

Malita answered 17/8, 2016 at 21:53 Comment(2)
I would imagine because .indexOf lacks the overhead of calling a function. some is probably more efficient for larger arrays.Ludicrous
Using different browsers, and running tests several times, I got different results. On Chrome 52, test2 is faster. On Firefox 50, test1 is faster. Not so sure then that one is faster than the other.Chaing
F
7

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.

Floriaflorian answered 17/8, 2016 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.