【问题标题】:Prevent Closure compiler from duplicating string防止闭包编译器复制字符串
【发布时间】: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


【解决方案1】:

此处记录了此行为:

http://code.google.com/p/closure-compiler/wiki/FAQ#Closure_Compiler_inlined_all_my_strings,_which_made_my_code_size

但是,当我添加一个非常大的值得重复数据删除的字符串时,我用来避免的一种方法是将值包装在一个函数中:

const getCssStyleSheetText = () =&gt; "...";

并在我需要文本时调用该函数。编译器在内联函数时使用不同的启发式算法,并且仅在估计会减少代码大小时才内联函数。因此,返回字符串的函数如果被调用一次就会被内联,但如果被多次调用则不做任何处理。

理想情况下,编译器对内联字符串会更加细致入微,但总的来说,它所采用的方法效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多