Initialise array with zeros

JavaScript performance comparison

Revision 9 of this test case created by Timo

Info

Create an array of predefined length filled entirely with zeros.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    // final array will be 1,000,000 elements long
    var numzeros = 1000*1000;
   
    // start from (arbitrarily chosen) sixteen zeros
    var zeros = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    var zeros2 = [];
};

Benchmark.prototype.teardown = function() {
    if (zeros.length != numzeros)
      alert('error: zeros.length is ' + zeros.length)
};
</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
Push
var l   = zeros.length,
    r   = numzeros - l; // remainder
for (var i=r; i--;) {
  zeros.push(0);
}
pending…
Concat
var l   = zeros.length,
    r   = numzeros - l; // remainder
while (r >= l) {
  r    -= l;
  l    += l;
  zeros = zeros.concat(zeros);
}
zeros = zeros.concat(zeros.slice(0, r));
pending…
Push.apply
var l   = zeros.length,
    r   = numzeros - l; // remainder
while (r >= l) {
  r    -= l;
  l    += l;
  zeros.push.apply(zeros, zeros);
}
zeros.push.apply(zeros, zeros.slice(0, r));
pending…
Push.apply -- for loop
var l   = zeros.length,
    r   = numzeros - l; // remainder
    n   = Math.floor(r / l),
    m   = r % l,
    nul = zeros.slice();
for (var i=n; i--; ) {
  zeros.push.apply(zeros, nul);
}
zeros.push.apply(zeros, zeros.slice(0, m));
pending…
Inline
zeros2 = zeros_source;
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