这种方式就是把循环展开,据说可以提高性能,但测试效果不明显,在谷歌50中展开反倒变慢了,IE10这种变快了。看来实际使用中中还是需要测试
测试代码:
function doProcess(value1, value2) {
return value1 + value2;
}
function createArr() {
var t = [];
for (var i = 0; i < 3000; i++) {
t[i] = i;
}
return t;
}
/*原始循环*/
function Test1() {
var t = createArr();
var date1 = new Date().getTime();
var total = 0;
var length = t.length;
for (var i = 0; i < length; i++) {
total = doProcess(total, t[i]);
}
var date12 = new Date().getTime();
console.log("1Test" + ((date12 - date1)));
}
/*循环展开*/
function Test2() {
var t = createArr();
var date1 = new Date().getTime();
var length = t.length;
var iteration = Math.floor(length / 8);
var leftover = length % 8;
var total = 0;
var i = 0;
if (leftover > 0) {
do {
total = doProcess(total, t[i++]);
}
while (--leftover > 0)
}
do {
total = doProcess(total, t[i++]);
total = doProcess(total, t[i++]);
total = doProcess(total, t[i++]);
total = doProcess(total, t[i++]);
total = doProcess(total, t[i++]);
total = doProcess(total, t[i++]);
total = doProcess(total, t[i++]);
total = doProcess(total, t[i++]);
}
while (--iteration > 0)
var date12 = new Date().getTime();
console.log("2Test" + ((date12 - date1)));
}
其实展开也是一种思路,对于具体的问题还需要具体的分析,根据业务在进行改写,例如:
/*原始循环*/
function Test1() {
var t = createArr();
var date1 = new Date().getTime();
var total = 0;
var total2 = 0;
var length = t.length;
for (var i = 0; i < length; i++) {
if(i%2)
{
total2 = doProcess(total2, t[i]);
}
else{
total = doProcess(total, t[i]);
}
}
var date12 = new Date().getTime();
console.log("1Test" + ((date12 - date1)));
console.log(total2+"Test" +total);
}
/*循环展开*/
function Test2() {
var t = createArr();
var date1 = new Date().getTime();
var total = 0;
var total2 = 0;
var length = t.length;
for (var i = 0; i < length; ) {
total2 = doProcess(total2, t[i]);
i+=2;
}
for (var i = 0; i < length; ) {
total = doProcess(total, t[i]);
i+=2;
}
var date12 = new Date().getTime();
console.log("2Test" + ((date12 - date1)));
console.log(total2+"Test" +total);
}
因为分开后,少了一次判断,速度就快了,如果有很多不同的处理,就会快很多。