<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>A Log on JavaScript &#187; js code optimization</title>
	<atom:link href="http://www.jslog.com/tag/js-code-optimization/feed" rel="self" type="application/rss+xml" />
	<link>http://www.jslog.com</link>
	<description></description>
	<lastBuildDate>Thu, 21 Jul 2011 11:00:10 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Google Closure Advanced Compilation</title>
		<link>http://www.jslog.com/google-closure-advanced-compilation</link>
		<comments>http://www.jslog.com/google-closure-advanced-compilation#comments</comments>
		<pubDate>Sun, 21 Mar 2010 21:24:10 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[Google Closure]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[utilities]]></category>
		<category><![CDATA[js code optimization]]></category>
		<category><![CDATA[obfuscation]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=171</guid>
		<description><![CDATA[As I have promised in this post, I am giving a review of the ADVANCED_OPTIMIZATIONS option in Google Closure JavaScript Compiler.
Beyond simply shortening variable names, Closure Compiler with ADVANCED_OPTIMIZATIONS, does three other important steps:

aggresive renaming &#8211; not only renaming local variables and functions, but it renames GLOBAL variables and functions. In this way, it can [...]]]></description>
			<content:encoded><![CDATA[<p>As I have promised in <a href="http://www.jslog.com/using-google-closure-compiler">this</a> post, I am giving a review of the <code>ADVANCED_OPTIMIZATIONS</code> option in Google Closure JavaScript Compiler.</p>
<p>Beyond simply shortening variable names, Closure Compiler with ADVANCED_OPTIMIZATIONS, does three other important steps:</p>
<ul>
<li><b>aggresive renaming</b> &#8211; not only renaming local variables and functions, but it renames GLOBAL variables and functions. In this way, it can ruin your public API</li>
<li><b>dead code removal</b> &#8211; it removes functions you are not using and segments of unreachable code. This can be fine for some apps, but it is definitely risky for JavaScript libraries, that expose some functions which are supposed to be called only by client code.</li>
<li><b>function inlining</b> &#8211; inserting the function&#8217;s body instead of the function call, where appropriate</li>
</ul>
<p>So it is true that without some additional work, the ADVANCED_OPTIMIZATIONS option will just ruin your code and your public API. Of course the solutions are at hand, but the question is if they worth the effort.
</p>
<p><span id="more-171"></span></p>
<p>
<h3>Keep your public API</h3>
<p>If you provide ONLY the code below to Google Compiler, it produces <b>empty</b> output:</p>
<pre class="prettyprint">
function hello(name){
    alert("Hello " + name);
}
</pre>
<p>What? Empty output? Well&#8230; yes, as you never call your function. Instead, for the next code: </p>
<pre class="prettyprint">
function hello(name){
    alert("Hello " + name);
}
hello('jslog');
</pre>
<p>it produces the following output:</p>
<pre class="prettyprint">
alert("Hello jslog");
</pre>
<p>This is smart! But we want to preserve our API (by the way, in the tutorial for Google Closure Compiler Advanced Optimizations, <a href="http://code.google.com/closure/compiler/docs/api-tutorial3.html">Google says on this page</a> that the <code>hello</code> function is preserved, while it is NOT &#8211; see section <a href="http://code.google.com/closure/compiler/docs/api-tutorial3.html#removal">Removal of code you want to keep</a> and try the code online at <a href="http://closure-compiler.appspot.com/home">Closure Compiler UI Tool</a>)
</p>
<p>
So if the <code>hello</code> method above would be part of the public API, it would break third parties using it. Google proposes a solution for this: export the public objects/functions into the global namespace using the <code>window</code> object:</p>
<pre class="prettyprint">
function hello(name){
    alert("Hello " + name);
}
hello('jslog');
window['hello'] = hello;

//and the output is:
function a(b){alert("Hello "+b)}a("jslog");window.hello=a;
//so the hello function is kept as a property on the global window object
</pre>
<p>Instead, if you use:</p>
<pre class="prettyprint">
window.hello = hello;
</pre>
<p>you get </p>
<pre class="prettyprint">
function b(c){alert("Hello "+c)}b("jslog");window.a=b;
</pre>
<p>which is surely not what you want. So make sure you use the <code>window['public_name']</code> notation. You should also standardize the way you access properties in your objects, either using the array notation, or the dotted notation, otherwise the compiler could be mislead by a mix of the two. But sometimes we just need to use both, as properties may be automatically generated at runtime.
</p>
<p>Other problems with the <b>Google Closure Compiler</b> <code>ADVANCED_OPTIMIZATIONS</code> are separately compiling blocks of code with dependencies to external JavaScript. The solution for this is </p>
<ul>
<li>using either <b>exports</b> like the above or with the <code>goog.exportSymbol()</code> or</li>
<li>using extern files specifically provided as a compilation option</li>
</ul>
<p>In any case, I think this is just a bit too clumsy. </p>
<p>Moreover, having a class and export all its properties/functions is quite a job to to if your app is already a large one. Just have a short example:</p>
<pre class="prettyprint">
MyClass = function(name) {
  this.myName = name;
};
MyClass.prototype.myMethod = function() {
  alert(this.myName);
};
window['MyClass'] = MyClass; // <-- Constructor
MyClass.prototype['myMethod'] = MyClass.prototype.myMethod; <-- export mechanism

//the above compiles to
MyClass=function(a){this.b=a};MyClass.prototype.a=function(){alert(this.b)};window.MyClass=MyClass;MyClass.prototype.myMethod=MyClass.prototype.a;
</pre>
</p>
<p>
<h3>Conclusions</h3>
<p>After this short overview of the <code>ADVANCED_OPTIMIZATIONS</code> flag, I really think most people won't need it. If you already have a large library, having it compiled with advanced optimizations would be a total nightmare, as it would require a review of all public methods and properties and additional work for each. And the gain? Just a few kilobytes. I have tried compiling <b>ExtJS Core with advanced optimizations and got aprox 62 KB</b>, while with <b>simple optimizations it is 74 KB</b>. Not very well for the amount of effort it would require, in my opinion. </p>
<p>But if you still think advanced optimizations is for you, you are probably wanting to optimize a lot, and you should first start seaching for other ways to optimize - first, make sure you combine all your js code into one file. It's better to have one js file of 100KB rather than have 10 files each of 5 KB. So make sure you are doing every other possible optimization before moving to the advanced optimizations flag.</p>
<p>After all, it's up to you to decide if it's worth the effort!
</p>
<p>PS: You can follow me on twitter <a href="http://twitter.com/extjslog">@extjslog</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/google-closure-advanced-compilation/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Using Google Closure Compiler</title>
		<link>http://www.jslog.com/using-google-closure-compiler</link>
		<comments>http://www.jslog.com/using-google-closure-compiler#comments</comments>
		<pubDate>Fri, 08 Jan 2010 22:06:04 +0000</pubDate>
		<dc:creator>radu</dc:creator>
				<category><![CDATA[Google Closure]]></category>
		<category><![CDATA[javascript minification]]></category>
		<category><![CDATA[js code optimization]]></category>
		<category><![CDATA[obfuscation]]></category>

		<guid isPermaLink="false">http://www.jslog.com/?p=61</guid>
		<description><![CDATA[JavaScript is evolving, and together with it, its ecosystem.
Google has launched a fantastic JavaScript &#8220;compiler&#8221; &#8211; Google Closure Compiler. The name is misleading, but the tool is great. This stands behind the famous apps from Google, like GMail, Google Maps, etc. Well, let&#8217;s see this in action.
What the compiler does is to minimize and obfuscate [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript is evolving, and together with it, its ecosystem.</p>
<p>Google has launched a fantastic JavaScript &#8220;<strong>compiler</strong>&#8221; &#8211; <a href="http://code.google.com/closure/compiler/">Google Closure Compiler</a>. The name is misleading, but the tool is great. This stands behind the famous apps from Google, like GMail, Google Maps, etc. Well, let&#8217;s see this in action.</p>
<p>What the compiler does is to minimize and obfuscate your JavaScript code. It has three levels of optimization: whitespace only, simple and advanced. There is nothing special about the whitespace only optimization. It&#8217;s clear what it does so let&#8217;s analyze a bit the other options! In this post I will introduce the <b>simple optimizations</b> option, and in a later post I will write an explanation about the <b>advanced optimizations level</b>.</p>
<h3>Simple Optimization Level</h3>
<p>This is the level you should play with first. It minimizes your code and also obfuscates it. Nothing new to this point. The good news is it also optimizes it and removes unreachable code or unused code.</p>
<pre class="prettyprint">// say we have this code... sayHi doesn't appear to be very useful
function hello(name) {
  function sayHi(){
     return "hi"
  }
  alert(name);
}
hello('New user');</pre>
<p>After &#8220;compilation&#8221; the code becomes:</p>
<pre class="prettyprint">function hello(a){alert(a)}hello("New user");</pre>
<p>Notice the name of the global <strong>hello</strong> function remained unchanged. This is good as this is our external API, and we don&#8217;t want to break it. Closure Compiler also renames parameters, local methods and identifiers. The <strong>name</strong> parameter has been renamed to <strong>a</strong>, and notice <strong>the unused sayHi method was removed</strong>.</p>
<p>Let&#8217;s see other samples as well:</p>
<pre class="prettyprint">function hello(name) {
  function sayHi(){
     return "hi"
  }
  return "greetings";
  alert(name);
}
hello('New user');</pre>
<p>has been compiled to</p>
<pre class="prettyprint">function hello(){return"greetings"}hello("New user");
//with one warning (not part of the generated code):
//JSC_UNREACHABLE_CODE: unreachable code at line 8 character 2
//  alert(name);
//  ^</pre>
<p>Wowww&#8230; that&#8217;s impressive. Notice the parameter to the <strong>hello</strong> method has been removed, as it is unused!</p>
<p>But what really got me is the &#8220;compilation&#8221; step. After all the name is not that misleading. Look at this</p>
<pre class="prettyprint">
function hello(){
   alert('hello world'
}
</pre>
<p>Well.. it&#8217;s obvious. But try and put that in your browser, and it will break your coolest app. You can avoid that with Google Closure. Here is the result:</p>
<pre class="prettyprint">
Number of errors: 2

JSC_PARSE_ERROR: Parse error. missing ) after argument list at line 4 character 1

JSC_PARSE_ERROR: Parse error. missing } after function body at line 4 character 1
</pre>
<p>Maybe this is one of the best parts of this &#8220;compiler&#8221;.
</p>
<p>I have tried some tests with the Google Compiler against some libraries. Here are the results:</p>
<table border="1px solid black">
<tr>
<th>Library</th>
<th>Library normal minified size</th>
<th>Library minified size with Google Closure</th>
</tr>
<tr>
<td>jQuery</td>
<td>55.9 KB</td>
<td>54 KB</td>
</tr>
<tr>
<td>ExtJS Core</td>
<td>78.9 KB</td>
<td>74 KB</td>
</tr>
</table>
<p>I though the results would be significantly better with &#8216;closure&#8217;, but you can see the difference is not that big. ExtJS uses <a href="http://developer.yahoo.com/yui/compressor/">YUICompressor</a> for minification and obfuscation. Maybe so does jQuery. So you can still use YUICompressor confidently. It would just be interesting to test on code which is badly written, with many unreachable statements and unoptimized.</p>
<p>I have  done the tests with jQuery and ExtJS using the <b>compiler.jar</b> Google offers. Simply run the compiler from command line on the library files, which have to be previously annotated with the following comments at the beginning of the files (these comments tell Google Compiler how to make the compilation): </p>
<pre class="prettyprint">
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
// ==/ClosureCompiler==
</pre>
<pre class="prettyprint">
java -jar compiler.jar --js=ext-core-debug.js --js_output_file=ext-core.pack.js
</pre>
<p>You can also use the webapp UI Google offers at <a href="http://closure-compiler.appspot.com/home">Google Closure Compiler Home</a>.<br />
I&#8217;ll come up with more details about the ADVANCED_OPTIMIZATIONS compilation in a later post.
</p>
<p>
Successful compilations!<br />
</></p>
]]></content:encoded>
			<wfw:commentRss>http://www.jslog.com/using-google-closure-compiler/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

