防止Closure编译器复制字符串 [英] Prevent Closure compiler from duplicating string

查看:74
本文介绍了防止Closure编译器复制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google的Closure编译器来缩小JS.我的代码中有几个地方有重复的字符串,例如

I'm using Google's Closure compiler to shrink my JS. There are several places in my code where I have a repeated string, e.g.

(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);

编译器并没有使冗余最小化(可以预料),所以我自己在预编译"代码中做到了:

The compiler wasn't minimizing that redundancy (to be expected) so I did it myself in the 'precompiled' code:

(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);

但是,当我通过编译器运行它时,它会逆转我的压缩,这会导致更多字符.它输出:

But when I run that through the compiler it reverses my compression, which results in more characters. It outputs:

(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);

有没有办法防止这种情况?知道为什么要这样做吗?这是运行时性能的改进吗?

Is there a way to prevent this? Any idea why it's being done? Is it a run-time performance improvement?

谢谢

推荐答案

此行为记录在这里:

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

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

However, one approach I've used to avoid when I have add a very large string that is worth deduplicating is to wrap the value in a function:

const getCssStyleSheetText = () => "...";

并在需要文本时调用该函数.内联函数时,编译器使用不同的试探法,并且仅在估计会减小代码大小的情况下才内联函数.因此,如果一次调用返回字符串的函数,则将内联,如果多次调用,则将其保留.

and to call that function when I need the text. The compiler uses a different heuristic when inlining functions and will only inline a function if it estimates that it will reduce code size. Therefore a function returning a string will be inlined if it is called once but left alone if it is called many times.

理想情况下,编译器在内联字符串方面会稍微有些细微差别,但总的来说,它采用的方法可以很好地解决问题.

Ideally, the compiler would be a little more nuanced about inlining strings but in general the approach it takes works out well enough.

这篇关于防止Closure编译器复制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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