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?
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:
So, the fastest, yet still very readable way is this. Unless you create
$arronly once and use it many times, there is no need for this and you can simply stay within_array().In case you did ask for JavaScript (in this case get rid of those
$prefixes!), the best solution is usingArray.indexOf():However, not all browsers already support
Array.indexOf(), so you might want to use e.g. the function from Underscore.js:jQuery also has a function for this:
The fastest way would be with an object and the
inoperator, but the object definition is less readable than the array definition: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.