forEach vs for function call

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
     var i,
            value,
            length,
            values = [],
            sum = 0,
            item = null,
            context = values;
       
       
        for (i = 0; i < 10000; i++) {
            values[i] = { value: Math.random() };
        }
       
        function add(obj) {
            sum += obj.value;
        }
};

Benchmark.prototype.teardown = function() {
        i = 0;
        value = 0;
        length = 0;
        values = [];
        sum = 0;
        item = null;
};
</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
forEach
values.forEach(add);
pending…
function call
for (i = 0; i < values.length; i++) {
    add(values[i]);
}
pending…
function call, item assign
for (i = 0; item = values[i]; i++) {
    add(item);
}
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