ArrayBuffer vs Typed Array in JavaScript

Introduction

In JavaScript, when it comes to handling binary data, two important concepts come into play: ArrayBuffer and Typed Array. These features provide a way to work with low-level binary data efficiently. In this article, I'll explain the differences between ArrayBuffer and Typed Array and examine their appropriate usage with suitable examples.

ArrayBuffer

ArrayBuffer is a built-in object in JavaScript that represents a fixed-length raw binary data buffer. It provides a way to allocate and manipulate raw binary data directly without the need for higher-level JavaScript objects. ArrayBuffer is essentially a container for storing binary data, and its size is determined at the time of creation and cannot be changed.

Key Features and Benefits of ArrayBuffer

  1. Raw Binary Data Storage: ArrayBuffer allows direct storage and manipulation of raw binary data, which can be useful in scenarios such as network protocols, file handling, and graphics processing.
  2. Efficient Memory Management: ArrayBuffer allocates a fixed amount of memory upfront, ensuring efficient memory usage for binary data storage.
  3. Shared Memory: Multiple views (Typed Arrays) can be created on a single ArrayBuffer, enabling efficient data sharing and manipulation across different views.

Let's have an example to understand the Arraybuffer

const buffer = new ArrayBuffer(20);

// Get the byte length of the buffer
const byteLength = buffer.byteLength;
console.log('Length of ArrayBuffer: '+byteLength); 

// Manipulate binary data using a DataView
const view = new DataView(buffer);
view.setUint8(0, 255); // Set the first byte to 255
const value = view.getUint8(0); // Get the value of the first byte
console.log('Value of the first byteP: '+value); 

Output

 

Typed Array

Typed Array is a JavaScript object that provides a way to access and manipulate raw binary data within an ArrayBuffer. Unlike ArrayBuffer, Typed Array provides a higher-level interface for working with binary data, offering various data types such as integers, floats, and bytes.

Key Features and Benefits of Typed Array

  1. Data Type Specification: Typed Array allows you to define the data type of the elements stored in the underlying ArrayBuffer, ensuring proper type handling and manipulation.
  2. Array-Like Interface: Typed Array objects have array-like properties and methods, enabling convenient access and manipulation of binary data.
  3. Efficient Data Processing: Typed Array provides optimized operations for manipulating binary data, such as bulk data copying, slicing, and numeric calculations.

Let's have an example to understand the Typed Array.

// Create a Typed Array with 4 signed 32-bit integers
const typedArray = new Int32Array(4);

// Set values to the array
typedArray[0] = 10;
typedArray[1] = 20;
typedArray[2] = 30;
typedArray[3] = 40;

// Iterate and perform calculations
let sum = 0;
for (let i = 0; i < typedArray.length; i++) {
  sum += typedArray[i];
}

console.log('sum of all the lements:'+sum); 

Output

Differences between ArrayBuffer and Typed Array

  • Purpose: ArrayBuffer is a low-level container for raw binary data storage, while Typed Array provides a higher-level interface for accessing and manipulating binary data.
  • Data Type Handling: ArrayBuffer does not enforce any specific data types and treats the data as raw binary. In contrast, Typed Array enforces data type specification, allowing for the proper handling of different types of binary data.
  • Memory Allocation: ArrayBuffer allocates a fixed amount of memory upon creation, whereas Typed Array objects are created based on a specific data type and take up memory according to the specified type and length.
  • Serialization and Transmission: ArrayBuffer is commonly used for serializing and transmitting binary data over the network or between different systems, as it provides a straightforward representation of the data. Typed Array objects are useful when you need to manipulate the data on the client side before or after transmission.
  • Size Flexibility: ArrayBuffer has a fixed size, determined at the time of creation, and cannot be resized. In contrast, Typed Arrays can have variable lengths and can be resized by creating a new Typed Array with the desired length.
  • Data Type Conversion: With ArrayBuffer, you have more flexibility in interpreting the data since it is treated as raw binary. You can read and interpret the binary data in different ways using a DataView. Typed Array objects, on the other hand, enforce a specific data type for the elements stored in the ArrayBuffer. This ensures the data is properly interpreted and manipulated according to the specified data type.
  • Usage and Manipulation: ArrayBuffer is mainly used as a data buffer, while Typed Array objects provide convenient array-like access and manipulation methods suitable for specific data types.

Let's have an example that will explain the differences between both objects.

const int8Array = new Int8Array(5);

// Set values to the Int8Array
int8Array[0] = 10;
int8Array[1] = 20;
int8Array[2] = 30;
int8Array[3] = 40;

// Calculate the sum of the values in the Int8Array
let sumTR = 0;
for (let i = 0; i < int8Array.length; i++) {
  sumTR += int8Array[i];
}

console.log('trying to sum of elements contained by typed array='+sumTR);

const buffer = new ArrayBuffer(5);

buffer[0] = 10;
buffer[1] = 20;
buffer[2] = 30;
buffer[3] = 40;

// Calculate the sum of the values in the buffer array
let sumBR = 0;
for (let i = 0; i < buffer.length; i++) {
  sumBR += buffer[i];
}

console.log('Trying to calculate the sum of same array with buffered array='+sumBR); 

Output

In this example, we can see that we are not getting some of the same elements in the case of a buffer array, but we are getting the result in the case of a typed array. we are getting 0 because ArrayBuffer itself does not provide direct access to the individual elements for assignment and retrieval.

Conclusion

ArrayBuffer and Typed Array are powerful features in JavaScript for handling binary data efficiently. While ArrayBuffer serves as a low-level container for raw binary data, Typed Array provides a higher-level interface for accessing and manipulating specific data types within an ArrayBuffer.

 FAQ's

Q. What is the difference between ArrayBuffer and Typed Array in JavaScript?

A. ArrayBuffer is a fixed-length raw binary data buffer, whereas Typed Array provides a higher-level interface for accessing and manipulating binary data within an ArrayBuffer. ArrayBuffer acts as a container for binary data, while Typed Array offers data type-specific views and convenient array-like manipulation methods.

Q. When should I use ArrayBuffer?

A. ArrayBuffer is primarily used as a low-level data buffer for storing and manipulating raw binary data. It is commonly employed in scenarios involving network protocols, file handling, and graphics processing.

Q. How do Typed Arrays enhance binary data handling?

A. Typed Arrays provide data type-specific views on an ArrayBuffer, allowing for efficient and convenient access and manipulation of binary data. They offer array-like properties and methods suitable for working with specific data types, such as integers, floats, and bytes.

Q. Can I resize an ArrayBuffer?

A. No, ArrayBuffer has a fixed size that is determined at the time of creation and cannot be resized. If you require variable-length storage, you can use Typed Arrays, which can be created with different lengths.

Q. What advantages does Typed Array offer over ArrayBuffer?

A. Typed Array provides benefits such as type enforcement, efficient data processing, array-like access and manipulation methods, and compatibility with various APIs. It simplifies working with binary data by offering higher-level abstractions and optimized operations for data manipulation.