create-2d-array-small

JavaScript performance comparison

Test case created by kamil-kielczewski

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var r=3
  var c=4

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
A
var arr = [];
for (var i = 0; i < r; i++) arr[i] = [];
return arr;
pending…
B
var arr = new Array(r);
for (var i = 0; i < arr.length; i++) arr[i] = new Array(c);
return arr;
pending…
C
var arr = Array(r);
for (var i = 0; i < arr.length; i++) arr[i] = Array(c);
return arr;
pending…
D
// strange, but works
var arr = [];
for (var i = 0; i < r; i++) {
  arr.push([]);
  arr[i].push(Array(c));
}
return arr;
pending…
E
let array = [[]];
for (var x = 0; x < c; x++) {
  array[x] = [];
  for (var y = 0; y < r; y++) array[x][y] = [0];
}
return array;
pending…
F
var makeArray = function(dims, arr) {
  if (dims[1] === undefined) {
    return Array(dims[0]);
  }

  arr = Array(dims[0]);

  for (var i = 0; i < dims[0]; i++) {
    arr[i] = Array(dims[1]);
    arr[i] = makeArray(dims.slice(1), arr[i]);
  }

  return arr;
}
return makeArray([r, c]);
pending…
G
var a = [];
while (a.push([]) < r);
return a;
pending…
H
function createArray(length) {
  var arr = new Array(length || 0),
      i = length;

  if (arguments.length > 1) {
      var args = Array.prototype.slice.call(arguments, 1);
      while(i--) arr[length-1 - i] = createArray.apply(this, args);
  }

  return arr;
}
return createArray(r,c);
pending…
I
return [...Array(r)].map(x => Array(c));
pending…
J
return Array(r).fill(0).map(() => Array(c));
pending…
K
return Array.from(Array(r), () => Array(c));
pending…
L
return Array.from({length: r}).map(e => Array(c));
pending…
M
return Array.from({length: r}, () => Array.from({length: c}, () => {}));
pending…
N
// 'esoteric solution': 
// save value: A[[1,2]]=6, read A[[1,2]] 
// (notice that instead A[1][2] we write A[[1,2]])

return {}
pending…
empty
// empty code only for theoretical max-speed comparison
pending…

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

0 Comments