Performance of OR operation ( || ) vs inArray()
javascript, jquery, performance
Solution
You don't want the fastest but the most readable way. And that's `in_array()` (JavaScript: `array.indexOf(value) >= 0`) for more than 2 or 3 values.
The performance difference is negligible - while a function call and array creation certainly has some overhead, it doesn't matter compared to expensive operations such a file access, database access, network access, etc.. So in the end nobody will notice the difference.
Here's a short benchmark, each with 1 million iterations:
5.4829950332642 - in_array, the array is recreated everytime
2.9785749912262 - in_array, the array is created only once
0.64996600151062 - isset(), the array way created only once and then the values were turned to keys using array_flip()
2.0508298873901 - ||
So, the fastest, yet still very readable way is this. Unless you create `$arr` only once and use it many times, there is no need for this and you can simply stay with `in_array()`.
$arr = array_flip(array('your', 'list', 'of', 'values'));
if(isset($arr[$value])) ...
In case you did ask for JavaScript (in this case get rid of those `$` prefixes!), the best solution is using `Array.indexOf()`:
['a', 'b', 'c'].indexOf(value) >= 0
However, not all browsers already support `Array.indexOf()`, so you might want to use e.g. the function from Underscore.js:
_.contains(['a', 'b', 'c'], value)
jQuery also has a function for this:
$.inArray(value, ['a', 'b', 'c'])
The fastest way would be with an object and the `in` operator, but the object definition is less readable than the array definition:
value in {'a':0, 'b':0, 'c':0}
Here's a JSPerf benchmark for the various solutions: http://jsperf.com/inarray-vs-or - but again, the rather big performance difference is negligible in most cases since you are not going to execute the code millions of times in a loop.
Problem
Suppose that you want to check what input string a user has entered in a form field. Which one would be the fastest way to check this input against a list of possible values? The following examples use jQuery. First method: using `||` ``` if (input == "firstValue" || input == "secondValue" || ... ) { ... } ``` Second method: using `inArray()` ``` if ($.inArray(input, array) >= 0) { ... } ``` Are there any significant differences between these two methods?