closure compiler 代码优化实例

2012-01-08 11:23

closure compiler 代码优化实例

by

at 2012-01-08 03:23:29

original http://yiminghe.iteye.com/blog/1337452

closure compiler 可以进行不少有意思的优化 ,一般只有在编译器优化中才会出现的,比如:

 

编译时计算(computation during compilation)

 

优化前:

 

var x=5*11;

alert(x*Math.random());

 

优化后:

 

优化时进行直接量计算,得到:

 

var x=55;
alert(x*Math.random());

 

高级模式下,甚至直接消除没有显式导出的变量 x:

 

alert(55*Math.random());

 

 

复写传播( copy propagation)

 

优化前

 

var x=Math.random()+1;
var y=x;
alert(y*Math.random());
alert(y);

 

 优化后

 

高级模式下,去除无意义的直接变量 copy 赋值以及未显式导出的 y,并替换所有使用 y 的地方为 x:

 

var a=Math.random()+1;alert(a*Math.random());alert(a);

 

 

无用代码消除 (useless code elimination)

 

上面的无用变量消除也算这一种,更广泛的应用是分支代码消除:

 

优化前:

 

if(1>2){ // if(debug)
alert(1);
}

 优化后为:

   

 但还有些没做的:

 

循环展开(loop unrolling)

 

优化前:

 

for(var i=0;i<3;i++){
alert(i);
}

 

优化后:

 

alert(1);
alert(2);
alert(3);

 

更好些,不过考虑到大多数循环代码比较长,以及 closure compiler 的重点在于减少代码体积,这点没加也是应该。

 

 

循环不变量迁移(motion of loop invariant)以及代码提升(code hoisting)

 

优化前:

 

var c=Math.random(),d=Math.random(),x=Math.floor(Math.random()*2);
 switch(x){
  case 0: 
    alert(c*d);
  break;
  case 1: 
    alert(c*d);
  break;
 }

 

var i,c=Math.random(),d=Math.random(),j;
 for(var i=0;i<10;i++){
   j=c*d+10;
 }

 期待优化后:

 

 

var c=Math.random(),d=Math.random(),x=Math.floor(2*Math.random()),t=c*d;switch(x){case 0:alert(t);break;case 1:alert(t)};

 

 

var i,c=Math.random(),d=Math.random(),j,t=c*d;for(i=0;10>i;i++)j=t+10;

 实际优化:

 

var c=Math.random(),d=Math.random(),x=Math.floor(2*Math.random());switch(x){case 0:alert(c*d);break;case 1:alert(c*d)};

 

var i,c=Math.random(),d=Math.random(),j;for(i=0;10>i;i++)j=c*d+10;

 

即将重复的 c*d 不变量提取出来。

 

虽然写出上述代码是程序员的责任,但工具如果能帮忙优化下显然会更好,希望 closure compiler 后续会考虑加入

 

 

 

 

 

 

          <br><br>
          <span style="color:red">
            <a href="http://yiminghe.iteye.com/blog/1337452#comments" style="color:red">已有 <strong>3</strong> 人发表留言,猛击-&gt;&gt;<strong>这里</strong>&lt;&lt;-参与讨论</a>
          </span>
          <br><br><br>

ITeye推荐