Various ways to call functions

JavaScript performance comparison

Revision 2 of this test case created by Chris Clower and last updated

Info

Tests just about every way a function can be called while getting the value of a global object and running an operation on that value. It ends up demonstrating how much faster operations run when values are cached.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var MyObject = {
      cake: function() {
        return 4;
      }
    };
   
    var cake = MyObject.cake();
   
    function Calculate(val, num) {
      return Math.pow(val, num);
    }
   
    var moreCake = Calculate(cake, 2);
   
    function Test1_ArgFunc(obj) {
      return Math.pow(obj.cake(), 2);
    }
   
    function Test2_CallFunc() {
      return Math.pow(this.cake(), 2);
    }
   
    function Test3_NoArg() {
      return Math.pow(MyObject.cake(), 2);
    }
   
    function Test4_CachedVal(val) {
      return Math.pow(val, 2);
    }
   
    var Test5_Cached2 = function(val) {
      return Math.pow(val, 2);
    };
   
    function Test6_DoubleCache() {
      return moreCake;
    }
   
    var Test7_DblCacheAnon = function() {
      return moreCake;
    }
};
</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
Function with Arg
Test1_ArgFunc(MyObject);
pending…
Function with Call
Test2_CallFunc.call(MyObject);
pending…
Function without Arg
Test3_NoArg();
pending…
Cached Value
Test4_CachedVal(cake);
pending…
Anonymous Function with Cached Val
Test5_Cached2(cake);
pending…
Double Cached
Test6_DoubleCache();
pending…
Double Cached Anonymous
Test7_DblCacheAnon();
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