[英]JavaScript performance: Call vs Apply
Is there a performance benefit in switching from func.apply(obj, params)
to func.call(obj)
when params
is an empty array or null
? 当
params
为空数组或null
时func.apply(obj, params)
从func.apply(obj, params)
切换到func.call(obj)
是否有性能优势?
I mean, is calling func.call(obj)
any faster than calling func.apply(obj, null)
? 我的意思是,调用
func.call(obj)
比调用func.apply(obj, null)
更快?
I'm mostly interested in performance under NodeJS 4.x. 我最感兴趣的是NodeJS 4.x下的性能。
This is for an algorithm that has to make a lot of such calls. 这适用于必须进行大量此类调用的算法。
On this page there is a comparison. 在这个页面上有一个比较。 https://jsperf.com/call-apply-segu Call was faster on my machine.
https://jsperf.com/call-apply-segu我的机器上的呼叫速度更快。
Ha, interesting: it looks like apply
is slower than call
. 哈,有意思:看起来
apply
比call
慢。 8-) 8-)
~/tmp ω cat test.js
function work(a, b, c) {
// do some work
}
var a = [1, 2, 3];
for (var j = 0; j < 4; j++) {
console.time('apply-ing');
for (var i = 0; i < 1000000; i++) {
work.apply(this, a);
}
console.timeEnd('apply-ing');
console.time('call-ing');
for (var i = 0; i < 1000000; i++) {
work.call(this, 1, 2, 3);
}
console.timeEnd('call-ing');
}
~/tmp ω node test.js
apply-ing: 42ms
call-ing: 5ms
apply-ing: 40ms
call-ing: 5ms
apply-ing: 42ms
call-ing: 5ms
apply-ing: 39ms
call-ing: 6ms
~/tmp ω node --version
v4.1.2
~/tmp ω
Basically, they will do the same steps: 基本上,他们将采取相同的步骤:
Function.prototype.apply ( thisArg , argArray )
Function.prototype.apply( thisArg , argArray )
- If IsCallable ( func ) is false, then throw a TypeError exception.
如果IsCallable ( func )为false,则抛出TypeError异常。
- If argArray is null or undefined , then
如果argArray为null或未定义 ,那么
- Return the result of calling the [[Call]] internal method of func , providing thisArg as the this value and an empty list of arguments.
返回调用func的[[Call]]内部方法的结果,提供thisArg作为此值和一个空的参数列表。
Function.prototype.call ( thisArg [ , arg1 [ , arg2 , … ] ] )
Function.prototype.call( thisArg [, arg1 [, arg2 ,...]])
- If IsCallable ( func ) is false , then throw a TypeError exception.
如果IsCallable ( func )为false ,则抛出TypeError异常。
- Let argList be an empty List .
让argList为空List 。
- If this method was called with more than one argument then in left to right order starting with arg1 append each argument as the last element of argList
如果使用多个参数调用此方法, 则从 arg1开始以从左到右的顺序将每个参数附加为argList的最后一个元素
- Return the result of calling the [[Call]] internal method of func , providing thisArg as the this value and argList as the list of arguments.
返回调用func的[[Call]]内部方法的结果,提供thisArg作为此值,并将argList作为参数列表。
So the difference, if any, should be implementation dependent, and negligible. 因此差异(如果有的话)应该依赖于实现,并且可以忽略不计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.