My understanding of JavaScript “compilation” is that it condenses and minifies your code to ultimately save bytes.
Does either condensing or minification make JavaScript run any faster?
Take the following examples for consideration:
var abcdefghijklmnopqrstuvwxyz = 1;
// vs.
var a=1;
var b = function() {
// Here is a comment
// And another
// White space
return true;
};
// vs.
var b=function(){return true}
I ran these examples through jsPerf with little or no difference.
Can compilation of JavaScript make it any faster or slower, in addition to saving bytes?
Minification does improve performance for two reasons: Reduced file-size (because it removes comments and unnecessary white spaces), so your script loads faster.
By reducing file sizes, JavaScript minification can improve webpage performance.
Minification means removing all the unnecessary characters from the source code without changing its functionality. These characters are needed to add readability to the code, but are not required for it to execute.
Minification will do nothing more from a security perspective than obfuscate your code from a casual browser. It's primary purpose is for performance. Rule of thumb: If you don't want the user to have access to it, don't send it to the client/browser.
Yes, compilation in the sense of the transforms applied by something like the Google Closure Compiler can make your script run faster. Consider this very simple example:
var x = ["hello", "james"].join(" ");
That compiles to:
var x="hello james";
Which is both less code and quicker to run. Obviously that's a silly example. I would hope you would write the compiled version yourself. However, it does demonstrate that Closure is capable of giving performance improvements as well as just file size improvements.
From the Closure docs (emphasis added):
The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript.
Edit
For an example of the Closure compiler actually increasing the size of a JavaScript file in an attempt to offer performance improvements, see my answer to this question.
Minified vs un-minified shouldn't make any difference in terms of execution speed. The only difference could be that minified version would be faster to parse, but even that when you have a very large file (you won't find any differences with the test you ran, it's just to small).
edit: the first statement I've made is valid if you are doing just the basic "minification". If you are using Closure compiler like James showed, then there could be some differences if the Clousure tools would optimize your code ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With