复制代码代码如下: // 创建一个8-byte的ArrayBuffer var b = new ArrayBuffer(8); // 创建一个b的引用,类型是Int32,起始位置在0,结束位置为缓冲区尾部 var v1 = new Int32Array(b); // 创建一个b的引用,类型是Uint8,起始位置在2,结束位置为缓冲区尾部 var v2 = new Uint8Array(b, 2); // 创建一个b的引用,类型是Int16,起始位置在2,总长度为2 var v3 = new Int16Array(b, 2, 2);
则缓冲和创建的引用布局为:
这表示Int32类型的v1数组的第0个元素是ArrayBuffer类型的b的第0-3个字节,如此等等。 上面我们通过ArrayBuffer来创建TypedArray,而实际上,TypedArray提供了3个html' target='_blank'>构造函数来创建他的实例。 构造函数 复制代码代码如下: TypedArray(unsigned long length) 创建一个新的TypedArray,length是其固定长度。
复制代码代码如下: // 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); } //
复制代码代码如下: // 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); } //