Function call overhead

JavaScript performance comparison

Test case created

Preparation code

<script>
  var test = [], limit = 100000;
 
  for (var i = 0; i < limit; i++) {
      test.push(Math.random());
  }
 
</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 call to loop
var test2 = 0;

for (var i = 0, n = test.length; i < n; i++) {
    test2 = test[i];
}
pending…
Looped function calls
var test2 = 0;

for (var i = 0, n = test.length; i<n; i++) {
    test2 = fun(test[i]);
}

function fun(num) {
    return(num);
}
pending…
Looped function calls with caching
var test2 = 0;
var testFunc = fun;

for (var i = 0, n = test.length; i<n; i++) {
    test2 = testFunc(test[i]);
}

function fun(num) {
    return(num);
}
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:

3 comments

Amaan commented :

What was the use of this test? Why would using a function to return it's own parameter be faster than just using the number itself?

James commented :

Its useful to see how slow a forEach iteration might be over a standard for loop. For each gives you some nice syntax but it will be a slower iteration.

Erik commented :

Very useful!

Add a comment