Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript multidimensional Typed array (Int8Array) example

I tried to use Typed arrays instead of arrays, to reduce memory:

function createarrayInt8(numrows,numcols,number){
       
	var arr = new Int8Array(numrows);
         
	for (var i = 0; i < numrows; ++i){
		var columns = new Int8Array(numcols);
		for (var j = 0; j < numcols; ++j){
			columns[j] = number;
		}
		arr[i] = columns;
	}
  
	return arr; 
}

But i can't create multidimensional Typed array. Why? Do i have to cast only the "number" var to Int8?

like image 347
Matthias Ma Avatar asked Sep 09 '26 14:09

Matthias Ma


1 Answers

A typed Int8Array can only hold 8-bit integers. So arr[i] = columns won't work since columns is of type Int8Array which cannot be converted to and stored (in any meaningful way) as a an 8-bit integer.

Solution: Either make arr a generic Array whose elements can be arrays or - probably the more advanced but usually more performant solution - store your multidimensional array as a single flat array of size numrows * numcols and access an element via arr[column + row * numcols]:

var numrows = 5, numcols = 4;
var arr = new Int8Array(numrows * numcols).fill(0);

arr[3 + 1 * numrows] = 1; // col = 3, row = 1

console.log (arr);
like image 111
le_m Avatar answered Sep 11 '26 03:09

le_m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!