简体   繁体   中英

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 ?

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.

On this page there is a comparison. https://jsperf.com/call-apply-segu Call was faster on my machine.

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 ω

Basically, they will do the same steps:

Function.prototype.apply ( thisArg , argArray )

  1. If IsCallable ( func ) is false, then throw a TypeError exception.
  2. If argArray is null or undefined , then
    1. 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 , … ] ] )

  1. If IsCallable ( func ) is false , then throw a TypeError exception.
  2. Let argList be an empty List .
  3. 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
  4. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM