JS 数组 array 操作性能优化笔记

2017-11-21  本文已影响0人  blue_avatar

本篇笔记主要记录 JS array 操作的性能优化


push()

用数组长度 arr[arr.length] = newItem; 来代替
性能测试实例

var arr = [1, 2, 3, 4, 5];
// bad
arr.push(6);
// good
arr[arr.length] = 6; // 
// console.log(items); => [1, 2, 3, 4, 5, 6]

unshift()

使用 concat() 代替
性能测试实例

var arr = [1, 2, 3, 4, 5];
// bad
arr.unshift(0);
// good
arr = [0].concat(arr); // 在 Mac OS X 10.11.1 下的 Chrome 47.0.2526.106 加快了 98%
 
// console.log(items); => [0, 1, 2, 3, 4, 5]

splice()

var items = ['one', 'two', 'three', 'four'];
items.splice(items.length / 2, 0, 'hello');
 
// console.log(items); => ['one', 'two', 'hello', 'three', 'four']

数组遍历

for(j = 0,len=arr.length; j < len; j++) {
   
}

JS几种数组遍历方式以及性能分析对比


上一篇 下一篇

猜你喜欢

热点阅读