我用“Javascript忍者的秘密”中的一个脚本测试了性能:
function isPrime(number) {
if (number < 2) {
return false;
}
for (let i = 2; i < number; i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
console.time("isPrime");
isPrime(1299827);
console.timeEnd("isPrime");
console.time("isPrime");
isPrime.apply(1299827);
console.timeEnd("isPrime");
结果是:
isPrime: 8.276ms
isPrime: 0.779ms看起来“应用”更快?
发布于 2018-09-10 11:27:27
您的比较是不准确的,因为传递给apply的第一个参数是被调用函数的this值,传递给apply的第二个参数是要用来调用函数的参数数组。因此,您的apply不会使用任何参数调用isPrime,因此不会运行迭代,因为当i为2且number为undefined时,不满足条件i < number
function isPrime(number) {
console.log('calling with ' + number);
if (number < 2) {
return false;
}
for (let i = 2; i < number; i++) {
if (number % i === 0) {
return false;
}
}
return true;
}
console.time("isPrime");
isPrime(1299827);
console.timeEnd("isPrime");
console.time("isPrime");
isPrime.apply(1299827);
console.timeEnd("isPrime");
如果您正确使用apply并传入undefined, [1299827],结果将与预期的非常相似。您还应该在毫秒级别使用performance.now()以获得比console更高的精度,尽管对于如此快速的操作,您可能看不到可能存在的差异:
function isPrime(number){
console.log('calling with ' + number);
if(number < 2) { return false; }
for(let i = 2; i < number; i++) {
if(number % i === 0) { return false; }
}
return true;
}
const t1 = performance.now();
isPrime(1299827);
const t2 = performance.now();
isPrime.apply(undefined, [1299827]);
console.timeEnd("isPrime");
const t3 = performance.now();
console.log(t2 - t1);
console.log(t3 - t2);
发布于 2018-09-10 11:33:29
.apply的语法为
function.apply(thisArg,argsArray)
第一个参数thisArg在调用函数时引用了'this‘的值,在本例中是isPrime.apply( 1299827 ),您传入了1299827作为'this’,但没有参数,所以它实际上是isPrime(),不会执行for循环,所以速度更快
有关.apply的更多信息,请单击此处https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
发布于 2018-09-10 11:47:30
你一定要看看这个。
参考:https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
这一点是Array.prototype.apply(context = this, args = []),所以你的代码是错误的。
将您的代码更改为以下代码。
// incorrect.
isPrime.apply(1299827);
// correct.
isPrime.apply(this, 1299827);https://stackoverflow.com/questions/52250662
复制相似问题