What to use: "typed array" or Dataview?

Asked

Viewed 50 times

1

In Ecmascript 6 there is a new class DataView, and "typed arrays" (apparently supported in Internet Explorer 10 and 11), used to manipulate ArrayBuffer's. What is the difference between DataView and typed arrays (Uint16Array, Int32Array, etc..)?

1 answer

1


Knowing that ArrayBuffer represents binary data in the browser memory (a collection of fixed-size bytes), the so-called "typed arrays" and the DataView allows us to manipulate this collection of ArrayBuffer: just read or modify numbers on the bytes of this collection.

Besides that the DataView can represent numbers of different types in a single ArrayBuffer, the difference is only how the bytes that form each number are ordered in the representation offered by the interface (endianness). For example, we will decompose the bytes of a number into 16 bits (2 bytes) into two different orders (hexadecimal representation):

  • (in big-endian) 01 00
  • (or in little-endian): 00 01

In these 2 orders (the best known), one reverse of the other. Endianness only applies to bytes that form the number itself.

The DataView defines the bytes of a number regardless of the endianness device/platform, always using big-endian (or "network-endianness"). It is said that this is useful because of internet/network transmissions.

Even using DataView it is still possible to apply the current platform endianness: just set the number manually using 8-bit (1 byte) integers, but it is easier to use Uint8Array then.

The typed arrays numbers Int8Array and Uint8Array are the only ones not affected by endianness, because they use only 1 byte of data from the ArrayBuffer to be represented.

console.log(
    `Uint8Array:
      ${new Uint8Array([ 0 ]).buffer.byteLength}`

  , `\nInt8Array:
      ${new Int8Array([ -129 ]).buffer.byteLength}`
);

This gives a basic idea, "if DataView better than typed arrays".

About the performance I don’t know much :|, it is just said that it is more efficient to manage the current platform endianness (the fastest for it), it shouldn’t cost much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.