admin管理员组文章数量:1290433
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;
}
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?
Share Improve this question asked Jul 14, 2016 at 18:10 Matthias MaMatthias Ma 1031 silver badge6 bronze badges 2- 1 Well, a typed array can only store values of its type. A uint8 array can therefore only store unsigned 8 bit integers, but not arrays (of uints). – le_m Commented Jul 14, 2016 at 18:18
- i almost thought so :). But how can it get a multidimensional array that stores only unsigned 8 bit integers to reduce the used memory? – Matthias Ma Commented Jul 14, 2016 at 18:25
1 Answer
Reset to default 11A 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);
本文标签: javascript multidimensional Typed array (Int8Array) exampleStack Overflow
版权声明:本文标题:javascript multidimensional Typed array (Int8Array) example - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741496150a2381845.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论