Array.indexOf如何比Array.some更有效 [英] How can Array.indexOf be more efficient than Array.some

查看:214
本文介绍了Array.indexOf如何比Array.some更有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的灵感来自于这个问题的竞争答案: indexOf with multiple arguments

This question is inspired from competing answers on this question: indexOf with multiple arguments

用户想知道一种有效的方法来测试数组中是否存在数组中给出的一个或多个整数。具体来说,给定一个数组和数字 123 124 125 ,如何判断给定数组中是否存在一个或多个这些整数。建议使用两种解决方案:

The user wanted to know an efficient way to test an array for the existence of one or more integers given in an array. Specifically, given an array and the numbers 123, 124, and 125, how can you tell if one or more of these integers exists in the given array. Two solutions were suggested:

使用 indexOf()

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var exists = array.indexOf(123) !== -1 || array.indexOf(124) !== -1 || array.indexOf(125) !== -1;

或者,使用 some()

var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var exists = array.some(function(item) {
  return item === 123 || item === 124 || item === 125;
});

indexOf() 和< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some#Polyfill =nofollow noreferrer> some() 找到成功匹配时短路,但我认为 some()实施会更快无匹配。但是,另一位用户指出 indexOf()解决方案更快

Both the ECMA-262 algorithms for indexOf() and some() short-circuit when finding a successful match, but I would have thought that the some() implementation would be faster when there are no matches. However, another user pointed out that the indexOf() solution is faster.

如果 indexOf()代码更有效,即使它必须遍历数组多次?

How is the indexOf() code more efficient even though it must iterate over the array more times?

推荐答案

事情是 - 你的问题高度依赖于标准本身,而不是标准的实施方式。

The thing is - your question is highly relies not on the standard itself, but on how the standard is implemented.

说不同引擎之间的结果可能不一致。

Said that, the results may be not consistent between different engines.

非常明显的假设存在开销调用函数某些引擎中的某个时间可能会通过内联函数调用和其他一些棘手的优化来缓解。

The very obvious assumption that "there is an overhead to call a function" some time in some engine might be mitigated by inlining a function call and some other tricky optimisations.

总结一下:没有一个正确的答案,并且任何不会使用任何ES实现引用的答案+运行时细节(cpu指令/操作码,使用的优化) - 只是一种推测。

To summarise: there is no single right answer to that, and any answer that would not use any references to the ES implementations + runtime details (cpu instructions/opcodes, optimisations used) - is simply a speculation.

这篇关于Array.indexOf如何比Array.some更有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆