Array Zero Fill

JavaScript performance comparison

Revision 10 of this test case created by Timo

Preparation code

<script>
  function t1(len) {
      var arr = new Array(len);
      while (len-- > 0) {
          arr[len] = 0;
      }
  }
 
  function t2(len) {
      var arr = new Array();
      while (len-- > 0) {
          arr[len] = 0;
      }
  }
 
  function t3(len) {
      var arr = new Array(len);
      for (var i = 0; i < len; i++) {
          arr[i] = 0;
      }
  }
 
  function t4(len) {
      var arr = new Array();
      for (var i = 0; i < len; i++) {
          arr[i] = 0;
      }
  }
 
  function t5(len) {
      var arr = new Array(len);
      for (var i = len; i > 0; i--) {
          arr[i] = 0;
      }
  }
 
  function t6(len) {
      var arr = new Array();
      for (var i = len; i > 0; i--) {
          arr[i] = 0;
      }
  }
function push(len)
{
  var zeros = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
  var l   = zeros.length,
    r   = len - l; // remainder
  for (var i=r; i--;) {
    zeros.push(0);
  }
}

</script>
<script>
Benchmark.prototype.setup = function() {
    var numzeros = 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];
};
</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
t1
t1(1000);
pending…
t2
t2(1000);
pending…
t3
t3(1000);
pending…
t4
t4(1000);
pending…
t5
t5(1000);
pending…
t6
t6(1000);
pending…
SLICE + PUSH
var numzeros = 1000;
var zeros2 = zeros.slice(0);
var l   = zeros2.length,
    r   = numzeros - l; // remainder
for (var i=r; i--;) {
  zeros2.push(0);
}
pending…
PUSH FUNCTION
push(1000);
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