Cost of creating inner function v2

JavaScript performance comparison

Test case created by T.J. Crowder

Info

Tests the cost of creating an inner function within an outer function which does real work.

Preparation code

<div id="target"></div>
<div id="working"></div>
<script>
Benchmark.prototype.setup = function() {
    function commonFunction(r) {
        return "Result is " + r;
    }
    function fooWithBar(id, a, b) {
        var div = document.getElementById(id),
            working = document.getElementById("working"),
            result;
   
        function bar(x, msg) {
            var r = x * b;
            div.innerHTML = commonFunction(r);
            working.innerHTML = msg;
            return r;
        }
   
        working.innerHTML = "Working...";
   
        if (a < 3) {
            result = bar(a * 2, "Done using &lt; 3 rule");
        }
        else {
            result = bar(a * 3, "Done using &gt;= 3 rule");
        }
        return result;
    }
   
    function fooWithoutBar(id, a, b) {
        var div = document.getElementById(id),
            working = document.getElementById("working"),
            result;;
   
        working.innerHTML = "Working...";
   
        if (a < 3) {
            result = (a * 2) * b;
            div.innerHTML = commonFunction(result);
            working.innerHTML = "Done using &lt; 3 rule";
        }
        else {
            result = (a * 3) * b;
            div.innerHTML = commonFunction(result);
            working.innerHTML = "Done using &gt;= 3 rule";
        }
   
        return result;
    }
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
With an inner function
if (fooWithBar("target", 2, 3) !== 12) throw "Error in test";
pending…
Without
if (fooWithoutBar("target", 2, 3) !== 12) throw "Error in test";
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment