【发布时间】:2011-11-09 05:36:48
【问题描述】:
我正在使用 Google 的 Closure 编译器来缩小我的 JS。我的代码中有几个地方有重复的字符串,例如
(function($){
$('.bat').append('<p>the red car has a fantastically wonderfully awe inspiringly world class engine</p><p>the blue car has a fantastically wonderfully awe inspiringly world class stereo</p><p>the green car has a fantastically wonderfully awe inspiringly world class horn</p>')
})(jQuery);
编译器并没有最大限度地减少冗余(意料之中),所以我在“预编译”代码中自己做了:
(function($){
var ch = ' car has a fantastically wonderfully awe inspiringly world class ';
$('.bat').append('<p>the red'+ch+'engine</p><p>the blue'+ch+'stereo</p><p>the green'+ch+'horn</p>')
})(jQuery);
但是当我通过编译器运行它时,它会反转我的压缩,从而产生更多字符。它输出:
(function(a){a(".bat").append("<p>the red car has a fantastically wonderfully awe inspiringly world class engine</p><p>the blue car has a fantastically wonderfully awe inspiringly world class stereo</p><p>the green car has a fantastically wonderfully awe inspiringly world class horn</p>")})(jQuery);
有没有办法防止这种情况发生?知道为什么要这样做吗?是运行时性能提升吗?
谢谢
【问题讨论】:
-
AFAIK,Closure 正在做正确的事情。变量
ch不在外部使用,它通过内联来节省字节(并提高性能)。您这样做的方式似乎不是避免“重复字符串”的任何解决方案。另外,请注意,尽管重复的字符串在存储方面看起来效率低下,但它们不会影响 gzip 压缩后的大小。
标签: javascript google-closure-compiler