Home Web Front-end H5 Tutorial Introduction to the new array TypedArray introduced in HTML5_html5 tutorial skills

Introduction to the new array TypedArray introduced in HTML5_html5 tutorial skills

May 16, 2016 pm 03:50 PM
new array

Arrays in Javascript are powerful guys:

You can not specify the length when creating it, but change the length dynamically. You can read it as an ordinary array, or use it as a stack. You can change the value and even the type of each element in an array.

Well, actually it is an object. For example, we can create an array like this:

Copy code
Code As follows:

var array = new Array(10);

The power and omnipotence of Javascript’s arrays bring us convenience. But in general:

Almighty things can be used in various environments, but they may not be suitable for all environments.

TypedArray appeared precisely to solve the problem of "too many things done" by arrays in Javascript.

Origin

TypedArray is a general fixed-length buffer type that allows reading binary data in the buffer.

It was introduced in the WEBGL specification to solve the problem of Javascript processing binary data.

TypedArray has been supported by most modern browsers. For example, you can create TypedArray using the following method:

Copy code
The code is as follows:

// Create an 8-byte ArrayBuffer
var b = new ArrayBuffer(8);
// Create a reference to b, the type is Int32, starting The position is 0, the end position is the end of the buffer
var v1 = new Int32Array(b);
// Create a reference to b, the type is Uint8, the starting position is 2, the end position is the end of the buffer
var v2 = new Uint8Array(b, 2);
// Create a reference to b, type is Int16, starting position is 2, total length is 2
var v3 = new Int16Array(b, 2 , 2);

then the buffered and created reference layout is:
变量 索引
  字节数
b = 0 1 2 3 4 5 6 7
  索引数
v1 = 0 1
v2 =   0 1 2 3 4 5
v3 =   0 1  

This means that the 0th element of the v1 array of type Int32 is the 0-3 bytes of b of type ArrayBuffer, and so on. Constructor

Above we created TypedArray through ArrayBuffer, but in fact, TypedArray provides 3 constructors to create his instances.

Constructor
Copy code
The code is as follows:

TypedArray(unsigned long length)
Create A new TypedArray, length is its fixed length.


Copy the code
The code is as follows:

TypedArray(TypedArray array)
TypedArray(type[] array)
Creates a new TypedArray, each element of which is initialized according to the array, and the elements are type-converted accordingly.


Copy the code
The code is as follows:

TypedArray(ArrayBuffer buffer, optional unsigned long byteOffset, optional unsigned long length)
Create a new TypedArray as a reference to the buffer, byteOffset is its starting offset, and length is its length.

So usually we create TypedArray in the following way:

Copy code
The code is as follows:

var array = new Uint8Array(10);

or:

Copy the code
The code is as follows:

var array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]);

Data Operation

TypedArray provides four methods: setter, getter, set and subarray for data operations.

Method getter type get(unsigned long index)

Returns the element at the specified index.

setter void set(unsigned long index, type value)

Set the element at the specified index to the specified value.

void set(TypedArray array, optional unsigned long offset) void set(type[] array, optional unsigned long offset)

Set the value according to the array, and offset is the offset position.

TypedArray subarray(long begin, optional long end)

Returns a new TypedArray, with the start bit being begin and the end bit being end.

For example, to read elements you can use :

var array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); alert(array[4]); //5

Setting elements can be used :

var array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); alert(array[4]); //5array[4] = 12;alert(array[ 4]); //12

Get a copy using :

var array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); var array2 = array.subarray(0); Array type

类型 大小 描述 Web IDL类型 C 类型
Int8Array 1 8位有符号整数 byte signed char
Uint8Array 1 8位无符号整数 octet unsigned char
Uint8ClampedArray 1 8位无符号整数 (clamped) octet unsigned char
Int16Array 2 16位有符号整数 short short
Uint16Array 2 16位无符号整数 unsigned short unsigned short
Int32Array 4 32位有符号整数 long int
Uint32Array 4 32位无符号整数 unsigned long unsigned int
Float32Array 4 32位IEEE浮点数 unrestricted float float
Float64Array 8 64位IEEE浮点数 unrestricted double double
Type Size Description Web IDL Type C type Int8Array 1 8-bit signed integer byte signed char Uint8Array 1 8-bit unsigned integer octet unsigned char Uint8ClampedArray 1 8-bit unsigned integer (clamped) octet unsigned char Int16Array 2 16-bit signed integer short short Uint16Array 2 16-bit unsigned integer unsigned short unsigned short Int32Array 4 32-bit signed integer long int Uint32Array 4 32-bit unsigned integer unsigned long unsigned int Float32Array 4 32-bit IEEE floating point number unrestricted float float Float64Array 8 64-bit IEEE floating point number unrestricted double double
Those who have played with canvas may find it familiar.

Because the array used to store image data in ImageData is of type Uint8ClampedArray.

For example:

var context = document.createElement("canvas").getContext("2d");var imageData = context.createImageData(100, 100);console.log(imageData.data);

which appears as in FireBug:

Uint8ClampedArray { 0=0, 1=0, 2=0, more...}

Why use TypedArray

We know that numbers in Javascript are 64-bit floating point numbers. For a binary image (each pixel of the image is stored as an 8-bit unsigned integer), if you want to use its data in a Javascript array, it is equivalent to using 8 times the memory of the image to store the data of an image. This is It's obviously unscientific. TypedArray can help us use only 1/8 of the original memory to store image data.

Or for WebSocket, using base64 for transmission is also a more expensive method, and switching to binary transmission may be a better method.

Of course, TypedArray has more benefits, such as better performance. Below we conduct some small tests to verify this.

The browsers participating in the test are :

FireFox 17.0.1 and Chrome 23.0.1271.97m

Test1: Sequential reading speed reading

Copy code
The code is as follows:

var timeArray1 = [];
var timeArray2 = [];
function check1(){
var array = new Uint8ClampedArray(5000000);
for(var i = array.length; i- -;){
array[i] = Math.floor(Math.random() * 100);
}
var temp;
var time1 = (new Date()).getTime( );
for(var i = array.length; i--;){
temp = array[i];
}
var time2 = (new Date()).getTime() ;
console.log(time2 - time1);
timeArray1.push(time2 - time1);
}
function check2(){
var array2 = new Array(5000000);
for(var i = array2.length; i--;){
array2[i] = Math.floor(Math.random() * 100);
}
var temp;
var time3 = (new Date()).getTime();
for(var i = array2.length; i--;){
temp = array2[i];
}
var time4 = (new Date()).getTime();
console.log(time4 - time3);
timeArray2.push(time4 - time3);
}
function timer(__fun, __time, __callback){
var now = 0;
function begin(){
var timeout = setTimeout(function(){
if(now !== __time){
now ;
__fun();
begin();
}else{
if(timeArray1.length && timeArray2.length){
console.log("timeArray1 == " timeArray1 ", average == " average(timeArray1));
console.log("timeArray2 == " timeArray2 ", average == " average(timeArray2));
}
__callback && __callback();
}
}, 100);
}
begin();
}
function average(__array){
var total = 0;
for(var i = __array .length; i--;){
total = __array[i];
}
return (total / __array.length);
}
timer(check1, 10, function( ){
timer(check2, 10);
});


It can be seen that the reading speed of Uint8ClampedArray is obviously faster than Array (the longer the bar, the more time it takes).

Test2: Random reading

Copy code
The code is as follows:

//……
function check1(){
var array = new Uint8ClampedArray(5000000);
for(var i = array.length; i--;){
array[i] = Math.floor(Math.random() * 100);
}
var temp;
var time1 = (new Date()).getTime();
for(var i = array.length; i--;){
temp = array[Math.floor(Math.random() * 5000000)];
}
var time2 = (new Date()).getTime();
console.log(time2 - time1);
timeArray1.push(time2 - time1);
}
function check2(){
var array2 = new Array(5000000);
for(var i = array2.length; i--;){
array2[i] = Math.floor(Math.random() * 100);
}
var temp;
var time3 = (new Date()).getTime();
for(var i = array2.length; i--;){
temp = array2[Math.floor(Math.random() * 5000000)];
}
var time4 = (new Date()).getTime();
console.log(time4 - time3);
timeArray2.push(time4 - time3);
}
//……

随即读取中Uint8ClampedArray的读取速度也是比Array要快的。

Test3:顺序写入

复制代码
代码如下:

//……
function check1(){
var array = new Uint8ClampedArray(5000000);
var time1 = (new Date()).getTime();
for(var i = array.length; i--;){
array[i] = Math.floor(Math.random() * 100);
}
var time2 = (new Date()).getTime();
console.log(time2 - time1);
timeArray1.push(time2 - time1);
}
function check2(){
var array2 = new Array(5000000);
var time3 = (new Date()).getTime();
for(var i = array2.length; i--;){
array2[i] = Math.floor(Math.random() * 100);
}
var time4 = (new Date()).getTime();
console.log(time4 - time3);
timeArray2.push(time4 - time3);
}
//……


Test4:复制操作(U8C to U8C 和 Array to U8C)




复制代码
代码如下:

//……
function check1(){
var array = new Uint8ClampedArray(5000000);
for(var i = array.length; i--;){
array[i] = Math.floor(Math.random() * 100);
}
var temp;
var array2 = new Uint8ClampedArray(5000000);
var time1 = (new Date()).getTime();
array2.set(array);
var time2 = (new Date()).getTime();
console.log(time2 - time1);
timeArray2.push(time2 - time1);
}
function check2(){
var array = new Array(5000000);
for(var i = array.length; i--;){
array[i] = Math.floor(Math.random() * 100);
}
var temp;
var array2 = new Uint8ClampedArray(5000000);
var time1 = (new Date()).getTime();
array2.set(array);
var time2 = (new Date()).getTime();
console.log(time2 - time1);
timeArray2.push(time2 - time1);
}
//……

可见U8C复制到U8C,比Array复制到U8C快得多。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run the h5 project How to run the h5 project Apr 06, 2025 pm 12:21 PM

Running the H5 project requires the following steps: installing necessary tools such as web server, Node.js, development tools, etc. Build a development environment, create project folders, initialize projects, and write code. Start the development server and run the command using the command line. Preview the project in your browser and enter the development server URL. Publish projects, optimize code, deploy projects, and set up web server configuration.

What exactly does H5 page production mean? What exactly does H5 page production mean? Apr 06, 2025 am 07:18 AM

H5 page production refers to the creation of cross-platform compatible web pages using technologies such as HTML5, CSS3 and JavaScript. Its core lies in the browser's parsing code, rendering structure, style and interactive functions. Common technologies include animation effects, responsive design, and data interaction. To avoid errors, developers should be debugged; performance optimization and best practices include image format optimization, request reduction and code specifications, etc. to improve loading speed and code quality.

How to make h5 click icon How to make h5 click icon Apr 06, 2025 pm 12:15 PM

The steps to create an H5 click icon include: preparing a square source image in the image editing software. Add interactivity in the H5 editor and set the click event. Create a hotspot that covers the entire icon. Set the action of click events, such as jumping to the page or triggering animation. Export H5 documents as HTML, CSS, and JavaScript files. Deploy the exported files to a website or other platform.

Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

What application scenarios are suitable for H5 page production What application scenarios are suitable for H5 page production Apr 05, 2025 pm 11:36 PM

H5 (HTML5) is suitable for lightweight applications, such as marketing campaign pages, product display pages and corporate promotion micro-websites. Its advantages lie in cross-platformity and rich interactivity, but its limitations lie in complex interactions and animations, local resource access and offline capabilities.

What is the H5 programming language? What is the H5 programming language? Apr 03, 2025 am 12:16 AM

H5 is not a standalone programming language, but a collection of HTML5, CSS3 and JavaScript for building modern web applications. 1. HTML5 defines the web page structure and content, and provides new tags and APIs. 2. CSS3 controls style and layout, and introduces new features such as animation. 3. JavaScript implements dynamic interaction and enhances functions through DOM operations and asynchronous requests.

What Does H5 Refer To? Exploring the Context What Does H5 Refer To? Exploring the Context Apr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

How to make pop-up windows with h5 How to make pop-up windows with h5 Apr 06, 2025 pm 12:12 PM

H5 pop-up window creation steps: 1. Determine the triggering method (click, time, exit, scroll); 2. Design content (title, text, action button); 3. Set style (size, color, font, background); 4. Implement code (HTML, CSS, JavaScript); 5. Test and deployment.

See all articles