call vs apply

JavaScript performance comparison

Revision 8 of this test case created by Madonna

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function Obj() {
      var that = "that";
    }
    Obj.prototype.target = function(test) {
      return test;
    };
   
    function fastApply(fn, target, args) {
      switch (args.length) {
      case 0:
        return fn.call(target);
      case 1:
        return fn.call(target, args[0]);
      case 2:
        return fn.call(target, args[0], args[1]);
      case 3:
        return fn.call(target, args[0], args[1], args[2]);
      case 4:
        return fn.call(target, args[0], args[1], args[2], args[3]);
      case 5:
        return fn.call(target, args[0], args[1], args[2], args[3], args[4]);
      case 6:
        return fn.call(target, args[0], args[1], args[2], args[3], args[4], args[5]);
      case 7:
        return fn.call(target, args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
      case 8:
        return fn.call(target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
      case 9:
        return fn.call(target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
      case 10:
        return fn.call(target, args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
      default:
        return fn.apply(target, args);
      }
    }
};
</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
Obj.prototype.target.apply(this, ["YES"]);
pending…
call
Obj.prototype.target.call(this, "YES");
pending…
fastApply
fastApply(Obj.prototype.target, this, "YES");
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