create-2d-array-fill-small

JavaScript performance comparison

Test case created by kamil-kielczewski

Preparation code


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

};
</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] = Array(c).fill(def);
return arr;
pending…
B
var arr = new Array(r);
for (var i = 0; i < arr.length; i++) arr[i] = new Array(c).fill(def);
return arr;
pending…
C
var arr = Array(r);
for (var i = 0; i < arr.length; i++) arr[i] = Array(c).fill(def);
return arr;
pending…
D
// strange, but works
var arr = [];
for (var i = 0; i < r; i++) {
  arr.push([]);
  arr[i].push(Array(c));
}
for (var i = 0; i < r; i++) for (var j = 0; j < c; j++) arr[i][j]=def
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] = def;
}
return array;
pending…
F
var makeArray = function(dims, arr) {
  if (dims[1] === undefined) {
    return Array(dims[0]).fill(def);
  }

  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(Array(c).fill(def)) < 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).fill(def);
  }

  return arr;
}
return createArray(r,c);
pending…
I
return [...Array(r)].map(x => Array(c).fill(def));
pending…
J
return Array(r).fill(0).map(() => Array(c).fill(def));
pending…
K
return Array.from(Array(r), () => Array(c).fill(def));
pending…
L
return Array.from({length: r}).map(e => Array(c).fill(def));
pending…
M
return Array.from({length: r}, () => Array.from({length: c}, () => def));
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]])

let arr={};
for (var i = 0; i < r; i++) for (var j = 0; j < c; j++) arr[[i,j]]=def;
return arr;
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