closure compiler 代码优化实例
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 后续会考虑加入。
?
?
?
?
?
?
1 楼 RednaxelaFX 2012-01-09 话说这帖里引用的术语的参考来源是什么地方?我读的资料里有好些术语都跟这里用的不一样。引用编译时计算(computation during compilation)
通常叫constant folding。也有时候被叫做partial evaluation但因为容易跟别的上下文里的别的用法弄混所以很少这么叫。
引用无用代码消除 (useless code elimination)
通常叫dead code elimination吧
引用循环不变量迁移(motion of loop invariant)
用词是对的,不过整个动作更常见的叫法是loop invariant code motion 2 楼 yiminghe 2012-01-09 不是龙/鲸书,找了本薄的复习下:http://detail.tmall.com/item.htm?id=15021680972&_u=9ba5ojmb784
RednaxelaFX 写道话说这帖里引用的术语的参考来源是什么地方? 3 楼 RednaxelaFX 2012-01-10 yiminghe 写道不是龙/鲸书,找了本薄的复习下:http://detail.tmall.com/item.htm?id=15021680972&_u=9ba5ojmb784
RednaxelaFX 写道话说这帖里引用的术语的参考来源是什么地方?
多谢,回头我也读读这本看写得如何