I just discovered that Javascript has typed arrays via this link. I was immediately curious what the benefit of such objects might be in the language.
I noticed that UInt8Arrays lose the .map()
-type functions that I would have for normal arrays objects so if you want to loop over them you would need a for
loop.
I assumed that I might be able to expect some performance boost when using UInt8Arrays but this doesn't seem to be the case.
var a = d3.range(225)
var b = new Uint8Array(d3.range(225))
console.time("a")
var result = 0;
for (var j = 10000; j >= 0; j--) {
for (var i = a.length - 1; i >= 0; i--) {
result += a[i];
};
};
console.timeEnd("a")
console.time("b")
var result = 0;
for (var j = 10000; j >= 0; j--) {
for (var i = b.length - 1; i >= 0; i--) {
result += b[i];
};
};
console.timeEnd("b")
I am using the d3 library to quickly generate a large array. This script gives the following output:
a: 2760.176ms
b: 2779.477ms
So the performance doesn't improve. The UInt8Array also doesn't throw an error when you insert a wrong value.
> new Uint8Array([1,2,3,4,'aasdf'])
[1,2,3,4,0]
With this in mind, what is the proper use case for UInt8Array
in Javascript? It seems like the normal array is a lot more flexible, equally robust and equally fast.