apply vs call vs invoke

JavaScript performance comparison

Revision 35 of this test case created by Luke

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function fn(a,b,c,d) {return a+b+c+d;}
    var obj = {};
    obj.fn = fn;
    function shit(fn, self, args){
      switch (self ? -1 : args.length) {
        case  0: return fn();
        case  1: return fn(args[0]);
        case  2: return fn(args[0], args[1]);
        case  3: return fn(args[0], args[1], args[2]);
        case  4: return fn(args[0], args[1], args[2], args[3]);
        case  5: return fn(args[0], args[1], args[2], args[3], args[4]);
        case  6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
        case  7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
        case  8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
        case  9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
        case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
        default: return fn.apply(self, args);
    }
    }
};

Benchmark.prototype.teardown = function() {
    delete obj.fn;
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
apply
fn.apply(obj, ['a','b','c','d']);
pending…
call
fn.call(obj, 'a', 'b', 'c', 'd');
pending…
invoke

obj.fn('a','b','c','d');
 
pending…
apply (undef)
fn.apply(undefined, ['a','b','c','d']);
pending…
call (undef)
fn.call(undefined, 'a', 'b', 'c', 'd');
pending…
invoke (undef)
fn('a','b','c','d');
 
pending…
shit
shit(fn, obj, ['a','b','c','d']);
pending…
shit (undef)
shit(fn, undefined, ['a','b','c','d']);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment