JavaScript typed array

  • JavaScript typed arrays are an array-like object and provide a mechanism for accessing raw binary data.
  • The objects stored in Array can dynamically increase and decrease, and can store any JavaScript value. The JavaScript engine will do some internal optimizations so that the operation of the array can be very fast.

Generally speaking, typed arrays are usually used with WebGL, and ArrayBuffers are everywhere when using WebGL. The browser communicates through WebGL and the graphics card. A large amount of real-time data interaction will occur between them. The performance requirements are particularly high. The data communication between them must be binary to meet the performance requirements, not traditional text. format.

Buffers and views: typed array architecture

In order to achieve maximum flexibility and efficiency, JavaScript typed arrays (Typed Arrays) split the implementation into two parts, buffer and view. A buffer (implemented by an ArrayBuffer object) describes a block of data. The buffer has no format at all and does not provide a mechanism to access its content. In order to access the memory contained in the buffer object, you need to use a view . The view provides the context—that is, the data type, the starting offset, and the number of elements—to convert the data into an actual typed array.
Insert picture description here

ArrayBuffer

ArrayBuffer is a data type used to represent a universal, fixed-length binary data buffer. You cannot directly manipulate the contents of an ArrayBuffer ; you need to create a view of a typed array or a DataView that describes the buffer data format, and use them to read and write the contents of the buffer

Data view

DataView is a low-level interface, which provides a read and write interface that can manipulate any data in the buffer. This is very helpful for scenarios that manipulate different types of data. For example, typed array views are all running in local endianness mode (see Endianness), and endianness can be controlled by using DataView. The default is Big-endian, but you can call the read and write interface to change to Little-endian.

Examples of use:

<script type="text/javascript">
	//创建一个16字节固定长度的缓冲
	var buffer = new ArrayBuffer(16);
	console.log("创建缓冲:")
	console.log(buffer)
	if (buffer.byteLength === 16) {
	  console.log("Yes, it's 16 bytes.");
	} else {
	  console.log("Oh no, it's the wrong size!");
	}
	// 创建视图
	// 此视图将把缓冲内的数据格式化为一个32位的有符号整数数组
	var int32View = new Int32Array(buffer);
	console.log("视图转换:")
	console.log(int32View)
	for (var i = 0; i < int32View.length; i++) {
	  int32View[i] = i * 2;
	}
	// 将类型化数组转换为普通数组
	var array = Array.from(int32View)
	console.log("普通数组:")
	console.log(array)
</script>

effect:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_36171287/article/details/111510183