Uint8Array Javascript usecase

I just discovered that Javascript has typed arrays using this link. I immediately wondered what the benefit of such objects could be in the language.

I noticed that UInt8Arrays will lose the .map() -type functions that I would use for regular array objects, so if you want to iterate over, you will need a for loop.

I suggested that I can expect some performance improvements when using UInt8Arrays, but this does not 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 use the d3 library to quickly create a large array. This script gives the following output:

 a: 2760.176ms b: 2779.477ms 

Thus, performance does not improve. UInt8Array also does not throw an error when entering an invalid value.

 > new Uint8Array([1,2,3,4,'aasdf']) [1,2,3,4,0] 

With that in mind, what is the correct use UInt8Array for UInt8Array in Javascript? A regular array seems to be much more flexible, equally strong and equally fast.

+2
javascript arrays
source share
1 answer

"Performance" usually does not mean how fast your script runs. There are also many other important factors, such as how quickly your computer freezes and / or crashes. Memory. The smallest javascript implementation in memory, usually allocated to var, is 32 bits. It means

 var a = true; 

in your memory looks like this:

 0000 0000 0000 0000 0000 0000 0000 0001 

This is a huge waste, but usually this is not a problem, since no one uses a significant enough number of them to really make a difference. Typed arrays are designed for cases where it matters, when you can actually reduce the amount of memory used by a huge amount, for example, when working with image data, audio data, or all kinds of raw binary data.

Another difference, which in some cases can potentially save even more memory, is that it allows you to work with data passed by reference, which you usually pass by value.

Consider this case:

 var oneImage = new Uint8Array( 16 * 16 * 4 ); var onePixel = new Uint8Array( oneImage.buffer, 0, 4 ); 

now you have 2 independent views on the same ArrayBuffer array working on the same data, applying this concept not only allows you to have one huge thing in your memory, but also allows you to divide it into as many segments as you currently want to work with little overhead, which is probably even more important.

+4
source share

All Articles