以下示例使用jQuery。
第一种方法:使用||。
if (input == "firstValue" || input == "secondValue" || ... ) {
...
}
第二种方法:使用
inArray()
。if ($.inArray(input, array) >= 0) {
...
}
这两种方法之间有显著的区别吗?
if (input == "firstValue" || input == "secondValue" || ... ) {
...
}
inArray()
。if ($.inArray(input, array) >= 0) {
...
}
你不需要最快的方法,而是最易读的方法。这时候使用 in_array()
(JavaScript: array.indexOf(value) >= 0
) 对于两个或三个以上的值来说更为合适。
性能差异可以忽略不计 - 尽管函数调用和数组创建肯定会有一些开销,但与文件访问、数据库访问、网络访问等昂贵的操作相比,这些开销微不足道。因此,在最终结果中,没有人会注意到区别。
这里是一个短小的基准测试,每个测试都执行了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 - ||
因此,最快且仍然非常易读的方法是这样的。除非你只创建$arr
一次并使用多次,否则没有必要这样做,你可以简单地使用in_array()
。
$arr = array_flip(array('your', 'list', 'of', 'values'));
if(isset($arr[$value])) ...
如果您确实需要 JavaScript (在这种情况下去掉那些$
前缀!), 最好的解决方案是使用Array.indexOf()
:
['a', 'b', 'c'].indexOf(value) >= 0
然而,并不是所有浏览器都已支持Array.indexOf()
,所以您可能需要使用例如Underscore.js中的函数:
_.contains(['a', 'b', 'c'], value)
jQuery 也有一个函数可以实现这个功能:
$.inArray(value, ['a', 'b', 'c'])
最快的方法是使用对象和 in
运算符,但是对象的定义不如数组定义易读:
value in {'a':0, 'b':0, 'c':0}
以下是不同解决方案的JSPerf基准测试:http://jsperf.com/inarray-vs-or - 但是,大多数情况下性能差异较大的影响可以忽略不计,因为您不会在循环中执行代码数百万次。
for(var i in array)
(您不应该这样做),扩展 Array.prototype
将会破坏这些循环。除此之外,OP 已经在使用 jQuery 了。 - ThiefMasterif (a || b || c)
。Array.indexOf()
。Object
,然后您可以使用 if (myVar in myKeyObj)
。 这应该会提供最差 O(log n)
的性能。O(log n)
?假设JavaScript使用哈希表进行对象键查找,那么它应该是O(1)
,不是吗? - ThiefMaster在大多数语言中,inArray()的实现方式如下:
function inArray(needle, haystack) {
for (i = 0; i < length; i++) {
if (haystack[index] == needle) {
return true;
}
}
return false;
}
if (haystack[0] == needle) {
return true;
}
if (haystack[1] == needle) {
return true;
}
if (haystack[3] == needle) {
return true;
}
// and so on
这可以简化为
if (haystack[0] == needle || haystack[2] == needle || … ) {
return true;
}
不改变底层的发生情况。
如果你经常需要查找这样的东西,我建议你了解一下地图,而不是
var haystack = ['hello', 'world', 'how', 'is', 'life'];
if (inArray("life", haystack)) {
// …
}
你需要做的是
var haystack = {'hello' : true, 'world' : true, 'how' : true, 'is' : true, 'life' : true};
if (haystack["life"]) {
// …
}
检查的元素越多,与数组相比,地图的性能将会更好。
在编写 JavaScript 时,通常性能不是一个大问题,并且通常很难回答。但在这个示例中,解决方案之间的关键区别在于扩展性。第一种解决方案总是会执行预定数量的比较,而 inArray 解决方案的扩展性较差,因为如果有更多的值,它将进行更多的比较。
然而,我仍然会选择 inArray,99.99% 的情况下,性能真的并不重要。您希望保持代码的可维护性,这更重要。
||
中得到 true,JavaScript / PHP 会提前退出,对吗? - Andreas Wong
inArray()
这样的函数,因为它具有更大的潜力来处理大型对比数据集。同时也更易于阅读。想象一下,如果我们需要对比10个或更多的值会是怎样的情况! :D - Richard Neil Ilagan