后增量与前增量 - Javascript优化 [英] post increment vs pre increment - Javascript Optimization

查看:23
本文介绍了后增量与前增量 - Javascript优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我偶然发现这个名为 JSpeed - Javascript 优化的项目时,我正在浏览 Google 代码.

I was browsing Google Code when I chanced upon this project called JSpeed - optimization for Javascript.

我注意到其中一项优化是将 for 循环语句中的 i++ 更改为 ++i.

I noticed one of the optimization was to change i++ to ++i in for loop statements.

优化前

for (i=0;i<1;i++) {}

for (var i = 0, j = 0; i < 1000000; i++, j++) {
    if (i == 4) {
        var tmp = i / 2;
    }

    if ((i % 2) == 0) {
        var tmp = i / 2;
        i++;
    }
}
var arr = new Array(1000000);
for (i = 0; i < arr.length; i++) {}

优化后

for(var i=0;i<1;++i){}
for(var i=0,j=0;i<1000000;++i,++j){if(i==4){var tmp=i>>1;}
if((i&1)==0){var tmp=i>>1;i++;}}
var arr=new Array(1000000);for(var i=0,arr_len=arr.length;i<arr_len;++i){}

我知道 pre 和 post 增量的作用,但知道这如何加快代码速度吗?

I know what pre and post increments do, but any idea how does this speeds the code up?

推荐答案

这是我读到的,可以回答你的问题:preincrement (++i) 给 i,然后返回i;相比之下,i++ 返回i,然后给它加一个,理论上 导致在应用增量操作之前创建一个临时变量来存储 i 的值".

This is what I read and could answer your question: "preincrement (++i) adds one to the value of i, then returns i; in contrast, i++ returns i then adds one to it, which in theory results in the creation of a temporary variable storing the value of i before the increment operation was applied".

这篇关于后增量与前增量 - Javascript优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆