Reputation: 25840
Is there a performance benefit in switching from func.apply(obj, params)
to func.call(obj)
when params
is an empty array or null
?
I mean, is calling func.call(obj)
any faster than calling func.apply(obj, null)
?
I'm mostly interested in performance under NodeJS 4.x.
This is for an algorithm that has to make a lot of such calls.
Upvotes: 1
Views: 4225
Reputation: 288230
Basically, they will do the same steps:
Function.prototype.apply (thisArg, argArray)
- If IsCallable(func) is false, then throw a TypeError exception.
- If argArray is null or undefined, then
- Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and an empty list of arguments.
Function.prototype.call (thisArg [ , arg1 [ , arg2, … ] ] )
- If IsCallable(func) is false, then throw a TypeError exception.
- Let argList be an empty 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
- Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and argList as the list of arguments.
So the difference, if any, should be implementation dependent, and negligible.
Upvotes: 2
Reputation: 1334
Ha, interesting: it looks like apply
is slower than call
. 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 ω
Upvotes: 1
Reputation: 4149
On this page there is a comparison. https://jsperf.com/call-apply-segu Call was faster on my machine.
Upvotes: 3