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;
}
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#.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With