Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript minification of comparison statements

I was looking over one of the minified js files generated by closure. I found that wherever I'm checking for equality between a variable and string like,

a == "13" || a == "40"

closure replaces it with

"13" == a || "40" == a

Why is this modification done? Is there some performance advantage here?

like image 260
Jophin Joseph Avatar asked Feb 13 '12 06:02

Jophin Joseph


People also ask

How do you do minification in JavaScript?

To minify JavaScript, try UglifyJS. The Closure Compiler is also very effective. You can create a build process that uses these tools to minify and rename the development files and save them to a production directory.

What is the best JavaScript Minifier?

UglifyJS is one of the most popular JavaScript minification tools. It can parse, minify and compress JavaScript code. Besides, the tool generates a source map file while compressing to track back to your original code.

Should you minify your JS?

It is important to minify your CSS and minimise JavaScript files so they can load faster on your web pages. There are many reasons why you should minify your CSS and JavaScript: Reduce file size: The more code there is in a file, the larger it will be. Minified code is usually much smaller than the original version.

Does minification improve performance?

Minification is the process of minimizing code and markup in your web pages and script files. It's one of the main methods used to reduce load times and bandwidth usage on websites. Minification dramatically improves site speed and accessibility, directly translating into a better user experience.


1 Answers

This is done as for a minor gzip compression advantage. If you have "x == 1" and "1 == x" the compiler switches it to "1 == x" in both cases and you get more regular code that compresses better. The win is so minor, that I've considered deleting the code and saving the cpu cycles, but it is on for now. It has nothing to do with preventing programmer errors as it will never switch "x = 2" into "2 = x" as that would change the meaning of the program.

like image 92
John Avatar answered Sep 19 '22 00:09

John