OR运算(||)与inArray()的性能

use*_*428 7 javascript performance jquery

假设您要检查用户在表单字段中输入的输入字符串.对于可能的值列表,哪一个是检查此输入的最快方法?

以下示例使用jQuery.

第一种方法:使用 ||

if (input == "firstValue" || input == "secondValue" || ... ) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

第二种方法:使用 inArray()

if ($.inArray(input, array) >= 0) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

这两种方法之间是否存在显着差异?

Thi*_*ter 17

你不想要最快但最可读的方式.这就是in_array()(JavaScript :) array.indexOf(value) >= 0超过2或3个值.

性能差异可以忽略不计 - 虽然函数调用和数组创建肯定会有一些开销,但与昂贵的操作(例如文件访问,数据库访问,网络访问等)相比无关紧要.所以最后没有人会注意到差异.

这是一个简短的基准测试,每个测试都有100万次迭代:

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 - ||
Run Code Online (Sandbox Code Playgroud)

因此,最快但仍然非常易读的方法就是这样.除非你创建$arr只有一次,并使用它很多次,没有必要为这一点,你可以简单地呆在一起in_array().

$arr = array_flip(array('your', 'list', 'of', 'values'));
if(isset($arr[$value])) ...
Run Code Online (Sandbox Code Playgroud)

如果你确实要求JavaScript(在这种情况下摆脱那些$前缀!),最好的解决方案是使用Array.indexOf():

['a', 'b', 'c'].indexOf(value) >= 0
Run Code Online (Sandbox Code Playgroud)

但是,并非所有浏览器都支持Array.indexOf(),因此您可能希望使用例如Underscore.js中的函数:

_.contains(['a', 'b', 'c'], value)
Run Code Online (Sandbox Code Playgroud)

jQuery还有一个功能:

$.inArray(value, ['a', 'b', 'c'])
Run Code Online (Sandbox Code Playgroud)

最快的方法是使用对象和in运算符,但是对象定义的可读性低于数组定义:

value in {'a':0, 'b':0, 'c':0}
Run Code Online (Sandbox Code Playgroud)

以下是针对各种解决方案的JSPerf基准测试:http://jsperf.com/inarray-vs-or - 但在大多数情况下,相当大的性能差异可以忽略不计,因为您不会在数百万次执行代码环.

  • 性能差异仅在实际检查运行很多次并且数组始终相同时才相关,即您可以创建一次数组然后重新使用它. (2认同)