I benchmarked it multiple times on Google Chrome 52, but feel free to copypaste it into any other browser's console.
~ 1500 ms, includes (~ 2700 ms when I used the polyfill)
var array = [0,1,2,3,4,5,6,7,8,9]; var result = 0; var start = new Date().getTime(); for(var i = 0; i < 10000000; i++) { if(array.includes("test") === true){ result++; } } console.log(new Date().getTime() - start);
~ 1050 ms, indexOf
var array = [0,1,2,3,4,5,6,7,8,9]; var result = 0; var start = new Date().getTime(); for(var i = 0; i < 10000000; i++) { if(array.indexOf("test") > -1){ result++; } } console.log(new Date().getTime() - start);
~ 650 ms, custom function
function inArray(target, array) { /* Caching array.length doesn't increase the performance of the for loop on V8 (and probably on most of other major engines) */ for(var i = 0; i < array.length; i++) { if(array[i] === target) { return true; } } return false; } var array = [0,1,2,3,4,5,6,7,8,9]; var result = 0; var start = new Date().getTime(); for(var i = 0; i < 10000000; i++) { if(inArray("test", array) === true){ result++; } } console.log(new Date().getTime() - start);
==operator? Do you really want to explicitly allow type coercion? Of course not. Therefore, use the===operator instead.countbefore the loop. You could also replace those two lines with justfor(var i=haystack.length; i--;)inoperator (e.g.(5 in array). It will probably be faster than other options, but won't work for string or objects or any other non-number.