Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Faster way to create and initialize two dimensional array (matrix)

Is there a faster way to create and zero out a matrix?
Currently, my code involves two for loops:

var nodes = new Array(ast.length);

for (var i=0; i < nodes.length; i++){
    nodes[i] = new Array(ast.length);
    for (var j=0; j < nodes.length; j++)
        nodes[i][j]=0;
}
like image 421
SaadH Avatar asked Jan 13 '16 18:01

SaadH


People also ask

How do you initialize a two-dimensional matrix?

Two-dimensional arrays may be initialized by specifying bracketed values for each row. int [,] a = new int [4,4] { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11} , {12, 13, 14, 15} }; The following is an example showing how to work with two-dimensional arrays in C#.

How do you create and initialize a 2D array?

To create an array use the new keyword, followed by a space, then the type, and then the number of rows in square brackets followed by the number of columns in square brackets, like this new int[numRows][numCols] . The number of elements in a 2D array is the number of rows times the number of columns.

How do you initialize a 2D array at run time?

Like the one dimensional array, 2D arrays can be initialized in both the two ways; the compile time initialization and the run time initialization. int table-[2][3] = { { 0, 2, 5} { 1, 3, 0} }; This way is the best way to initialize the 2D array. It also increases the readability of the user.


2 Answers

Since you asked for "faster", it looks like you can gain some speed by creating a single initalized array and then using .slice() to copy it rather than initializing each array itself:

var nodes = new Array(ast.length);
var copy = new Array(ast.length);
for (var i = 0; i < ast.length; i++) {
    copy[i] = 0;
}

for (var i=0; i < nodes.length; i++){
    nodes[i] = copy.slice(0);
}

jsperf test: http://jsperf.com/slice-vs-for-two-d-array/2

This method looks to be 10-20% faster in all three major browsers.

enter image description here

like image 159
jfriend00 Avatar answered Sep 25 '22 01:09

jfriend00


You can create array of zeros once and create copies of it:

var length = 10;

var zeros = Array.apply(null, Array(length)).map(Number.prototype.valueOf, 0);
var nodes = zeros.map(function(i) {
    return zeros.slice();
});

console.log(nodes);
like image 22
madox2 Avatar answered Sep 26 '22 01:09

madox2