Why use javaScript typed arrays

Elliot andersonElliot anderson
2 min read

First of all what is the is typed array

JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers.

You can read more details from JS-TYPE-ARRAYS

So when i read about js typed array i cant find answer about

Why use it in our project and after searching a lot about it, I found an article and code about it.

Type insurance

Let’s suppose you want numeric, or specifically Uint8 values at some function for the purpose of analyzing or processing bytes. If a Uint8Array is passed to this function, then the function does not have to make safety checks and validations on the type and the code will be cleaner.

Nonverbal communication

Other developers will have an easy time understanding what values such an array will contain, while an array with unspecified element type may contain “anything”.

Memory optimization

Let’s suppose you are storing 1024 integer values in this array. If you use up a single byte per item, then you are using only 1 KB for the items of this array.

Example

Consider a clinic where there are 3 queues of patients, surface patients, critical patients and emergency patients, each of these queues are 10–20–30 long respectively, and there should not be more than these amounts of disruption in the queue and the clinic. How do you implement such a structure?

We need 3 type arrays with the following names

  • Superficial patients (Max Patients 10)

  • Critical patients (Max Patients 20)

  • Emergency patients (Max Patients 30)

const patientsBuffer = new ArrayBuffer(30);

const superficialPatients = new Uint8Array(patientsBuffer, 0, 10);
const criticalPatients = new Uint8Array(patientsBuffer, 0, 20);
const emergencyPatients = new Uint8Array(patientsBuffer, 0, 30);

console.log(emergencyPatients.byteLength); // 10
console.log(emergencyPatients.length); // 30
console.log(criticalPatients[0]); // 0, the initial value

As you have seen, we were able to create arrays by using ArrayBuffer & Uint8Array , which in the first step is the optimal use of memory storage.
second stage
The limit of the range of each queue
The third step is the readability and cleanliness of the code.

Use array-typed Optimize your program and Enjoy Coding

Thanks for reading this short article.

Elliot .

0
Subscribe to my newsletter

Read articles from Elliot anderson directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Elliot anderson
Elliot anderson

Just Chill