4

Unit8Array is a typed array represents an array of 8-bit unsigned integers.

This is what I learnt from MDN. But why should we use Unit8Array specifically? Why not use a plain array instead? Why is Unit8Array often related to binary data?

veryverde
  • 444
  • 3
  • 13
krave
  • 1,629
  • 4
  • 17
  • 36
  • 1
    read MDN docs on ArrayBuffer, DataView - see if that enlightens you – Jaromanda X Jun 07 '21 at 08:16
  • Does this answer your question? [Uint8Array Javascript usecase](https://stackoverflow.com/questions/26319531/uint8array-javascript-usecase) – veryverde Jun 07 '21 at 08:21
  • @MichalBurgunder I have read that answer and no, it does not clear my confusion. – krave Jun 07 '21 at 08:25
  • 1
    Unit8Array uses less memory. So for memory heavy applications (e.g. image recognition), this will save signficant amount of space. Plus, it's typed, so you can be sure that binary data in this array isn't "corrupted" with strings, objects, etc. It's also cleaner to program with, because other developers reading your code know what's in it. Does that help? If not, what are you confused about? – veryverde Jun 07 '21 at 08:41
  • @MichalBurgunder Thanks, Michal. I went to MDN and read some materials about ArrayBuffer and DataView as Jaromanda X refered to. Now I know that ArrayBuffer gives us one way to inspect the buffer in a specific format. But what does a buffer do? Say if there is a `new ArrayBuffer(8)` and a 1GB file to be consumed by the buffer, is it true that the buffer reads 8-bytes many times from the file until the end of the file? We can not use buffer directly so we need something like Unit8Array do help us. Does Unit8Array get all the 1GB immediately after I invoked `new Unit8Array(something)`? – krave Jun 07 '21 at 10:44
  • There is so many types of TypedArray listed here. How could I know which to choose to use? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#typedarray_objects – krave Jun 07 '21 at 10:54
  • In essence, if the Javascript memory allows for it, yes. Buffers are basically glorified arrays, used for moving around unformatted data (e.g. pure binary data). Putting them into an array, you might get the type from (number vs String), which could cause huge problems. Which buffer/typed array you use, depends on the data you're dealing with. Black white photos, maybe an Int8Array. Color, perhaps Int16Array. It all depends on what you're doing. – veryverde Jun 07 '21 at 11:52
  • Are there some references about in which situation which typed array is more suitable and why? – krave Jun 07 '21 at 12:46

0 Answers0