looping

JavaScript performance comparison

Revision 8 of this test case created

Info

I have an array, I want a new array where I do something to it, how do I do it fastest.

Preparation code

<script src="//raw.github.com/documentcloud/underscore/master/underscore-min.js">
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var _len = 10000;
    var a = new Array(_len);
    while (_len--) {
      a[_len] = _len;
    }
    var f = function(a) {
        return a * a;
        }
};
</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
while --
var i = a.length;
var out = new Array(i);
while (i--) {
  out[i] = f(a[i]);
}
pending…
do/while
var i = a.length;
var out = new Array(i);
i--;
do {
  out[i] = f(a[i]);
}
while (i--);
pending…
while push
var i = 0;
var len = a.length;
var out = [];
while (i !== len) {
  out.push(f(a[i]));
  i++
}
pending…
while++!==
var i = 0;
var len = a.length;
var out = new Array(len);
while (i !== len) {
  out[i] = f(a[i]);
  i++
}
pending…
while++<
var i = 0;
var len = a.length;
var out = new Array(len);
while (i < len) {
  out[i] = f(a[i]);
  i++
}
pending…
for --
var i = a.length;
var out = new Array(i);
for (; i--;) {
  out[i] = f(a[i]);
}
pending…
for++;!==
var len = a.length;
var out = new Array(len);
for (var i = 0; i !== len; i++) {
  out[i] = f(a[i]);
}
pending…
for++;<
var len = a.length;
var out = new Array(len);
for (var i = 0; i < len; i++) {
  out[i] = f(a[i]);
}
pending…
map
var out = a.map(f);
pending…
jQuery map
var out = $.map(a, f);
pending…
underscore map
var out = _.map(a, f);
pending…
forEach
var out = new Array(a.length);
a.forEach(function(v, i) {
  out[i] = f(v);
});
pending…
while++< with no init size
var i = 0;
var len = a.length;
var out = [];
while (i < len) {
  out[i] = f(a[i]);
  i++
}
pending…
underscore each
var out = new Array(a.length);
_.each(out, function(v, i) {
  out[i] = f(v);
});
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