参见英文答案 >
Why most JavaScript native functions are slower than their naive implementations?1个
我想对我正在使用的函数进行基准测试,以确定对象数组中是否存在使用map()和some()的重复属性与另一个执行相同操作但在另一个内部使用for()的函数( ).
Click here to check the benchmark @H_502_5@有人能解释一下为什么吗? @H_502_5@编辑:这个问题与这个问题重复:Why most JavaScript native functions are slower than their naive implementations?
我想对我正在使用的函数进行基准测试,以确定对象数组中是否存在使用map()和some()的重复属性与另一个执行相同操作但在另一个内部使用for()的函数( ).
let array = [ { "value": 41},{ "value": 12},{ "value": 32} ]; let itens = array.map(x => x.value); let haveDuplicate = itens.some((item,idx) => itens.indexOf(item) !== idx);@H_502_5@与:
let array = [ { "value": 41},{ "value": 32} ]; let haveDuplicate = false; for (let i = 0; i < array.length; i++) { let x = array[i]; for (let j = (i + 1); j < array.length; j++) { if (array[j]) { let y = array[j]; if (x.value === y.value) { haveDuplicate = true; return; } else { haveDuplicate = false; } } } }@H_502_5@使用JsPerf我可以看到使用map()和some()的函数运行速度慢了90%~100%.
Click here to check the benchmark @H_502_5@有人能解释一下为什么吗? @H_502_5@编辑:这个问题与这个问题重复:Why most JavaScript native functions are slower than their naive implementations?
解决方法
循环版本更快的原因很少.
@H_502_5@> .map版本可能有调用函数的开销,这需要分配内存,推送到堆栈,一些运行时检查函数是否可调用等等.它可能会得到优化,或者不会.
>代码不等同. .indexOf需要扫描整个数组,如果item不存在,那么for循环版本第二个循环并不总是扫描整个数组. @H_502_5@此外,您最好使用Set(或只是对象incase Set不可用)来执行重复检查. @H_502_5@选择正确的数据结构/算法通常是最重要的优化步骤.
>代码不等同. .indexOf需要扫描整个数组,如果item不存在,那么for循环版本第二个循环并不总是扫描整个数组. @H_502_5@此外,您最好使用Set(或只是对象incase Set不可用)来执行重复检查. @H_502_5@选择正确的数据结构/算法通常是最重要的优化步骤.
let itens = array.map(x => x.value); haveDuplicate = new Set(itens).size !== itens.length