1.0.3 • Published 7 years ago

optimize-js v1.0.3

Weekly downloads
16,198
License
Apache-2.0
Repository
github
Last release
7 years ago

optimize-js Build Status JavaScript Style Guide

Optimize a JavaScript file for faster initial execution and parsing, by wrapping all immediately-invoked functions or likely-to-be-invoked functions in parentheses.

See the changelog for recent changes.

Install

npm install -g optimize-js

Usage

optimize-js input.js > output.js

Example input:

!function (){}()
function runIt(fun){ fun() }
runIt(function (){})

Example output:

!(function (){})()
function runIt(fun){ fun() }
runIt((function (){}))

Benchmark overview

BrowserTypical speed boost/regression using optimize-js
Chrome 5520.63%
Edge 1413.52%
Firefox 508.26%
Safari 10-1.04%

These numbers are based on a benchmark of common JS libraries. For benchmark details, see benchmarks.

CLI

Usage: optimize-js [ options ]

Options:
  --source-map  include source map                                     [boolean]
  -h, --help    Show help                                              [boolean]

Examples:
  optimize-js input.js > output.js    optimize input.js
  optimize-js < input.js > output.js  read from stdin, write to stdout

JavaScript API

var optimizeJs = require('optimize-js');
var input = "!function() {console.log('wrap me!')}";
var output = optimizeJs(input); // "!(function() {console.log('wrap me!')})()"

You can also pass in arguments:

var optimizeJs = require('optimize-js');
var input = "!function() {console.log('wrap me!')}";
var output = optimizeJs(input, {
  sourceMap: true
}); // now the output has source maps

Why?

Modern JavaScript engines like V8, Chakra, and SpiderMonkey have a heuristic where they pre-parse most functions before doing a full parse. The pre-parse step merely checks for syntax errors while avoiding the cost of a full parse.

This heuristic is based on the assumption that, on the average web page, most JavaScript functions are never executed or are lazily executed. So a pre-parse can prevent a slower startup time by only checking for what the browser absolutely needs to know about the function (i.e. whether it's syntactically well-formed or not).

Unfortunately this assumption breaks down in the case of immediately-invoked function expressions (IIFEs), such as these:

(function () { console.log('executed!') })();
(function () { console.log('executed Crockford-style!') }());
!function () { console.log('executed UglifyJS-style!') }();

The good news is that JS engines have a further optimization, where they try to detect such IIFEs and skip the pre-parse step. Hooray!

The bad news, though, is that these heuristics don't always work, because they're based on a greedy method of checking for a '(' token immediately to the left of the function. (The parser avoids anything more intricate because it would amount to parsing the whole thing, negating the benefit of the pre-parse). In cases without the paren (which include common module formats like UMD/Browserify/Webpack/etc.), the browser will actually parse the function twice, first as a pre-parse and second as a full parse. This means that the JavaScript code runs much more slowly overall, because more time is spent parsing than needs to be. See "The cost of small modules" for an idea of how bad this can get.

Luckily, because the '(' optimization for IIFEs is so well-established, we can exploit this during our build process by parsing the entire JavaScript file in advance (a luxury the browser can't afford) and inserting parentheses in the cases where we know the function will be immediately executed (or where we have a good hunch). That's what optimize-js does.

More details on the IIFE optimization can be found in this discussion. Some of my thoughts on the virtues of compile-time optimizations can be found in this post.

FAQs

How does it work?

The current implementation is to parse to a syntax tree and check for functions that:

  1. Are immediately-invoked via any kind of call statement (function(){}(), !function(){}(), etc.)
  2. Are passed in directly as arguments to another function

The first method is an easy win – those functions are immediately executed. The second method is more of a heuristic, but tends to be a safe bet given common patterns like Node-style errbacks, Promise chains, and UMD/Browserify/Webpack module declarations.

In all such cases, optimize-js wraps the function in parentheses.

But... you're adding bytes!

Yes, optimize-js might add as many as two bytes (horror!) per function, which amounts to practically nil once you take gzip into account. To prove it, here are the gzipped sizes for the libraries I use in the benchmark:

ScriptSize (bytes)Difference (bytes)
benchmarks/create-react-app.min.js160387
benchmarks/create-react-app.min.optimized.js160824+ 437
benchmarks/immutable.min.js56738
benchmarks/immutable.min.optimized.js56933+ 195
benchmarks/jquery.min.js86808
benchmarks/jquery.min.optimized.js87109+ 301
benchmarks/lodash.min.js71381
benchmarks/lodash.min.optimized.js71644+ 263
benchmarks/pouchdb.min.js140332
benchmarks/pouchdb.min.optimized.js141231+ 899
benchmarks/three.min.js486996
benchmarks/three.min.optimized.js487279+ 283

Is optimize-js intended for library authors?

Sure! If you are already shipping a bundled, minified version of your library, then there's no reason not to apply optimize-js (assuming you benchmark your code to ensure it does indeed help!). However, note that optimize-js should run after Uglify, since Uglify strips extra parentheses and also negates IIFEs by default. This also means that if your users apply Uglification to your bundle, then the optimization will be undone.

Also note that because optimize-js optimizes for some patterns that are based on heuristics rather than known eagerly-invoked functions, it may actually hurt your performance in some cases. (See benchmarks below for examples.) Be sure to check that optimize-js is a help rather than a hindrance for your particular codebase, using something like:

<script>
var start = performance.now();
</script>
<script src="myscript.js"></script>
<script>
var end = performance.now();
console.log('took ' + (end - start) + 'ms');
</script>

Note that the script boundaries are actually recommended, in order to truly measure the full parse/compile time. If you'd like to avoid measuring the network overhead, you can see how we do it in our benchmarks.

You may also want to check out marky, which allows you to easily set mark/measure points that you can visually inspect in the Dev Tools timeline to ensure that the full compile time is being measured.

Also, be sure to test in multiple browsers! If you need an Edge VM, check out edge.ms.

Shouldn't this be Uglify's job?

Possibly! This is a free and open-source library, so I encourage anybody to borrow the code or the good ideas. :)

Why not paren-wrap every single function?

As described above, the pre-parsing optimization in browsers is a very good idea for the vast majority of the web, where most functions aren't immediately executed. However, since optimize-js knows when your functions are immediately executed (or can make reasonable guesses), it can be more judicious in applying the paren hack.

Does this really work for every JavaScript engine?

Based on my tests, this optimization seems to work best for V8 (Chrome), followed by Chakra (Edge), followed by SpiderMonkey (Firefox). For JavaScriptCore (Safari) it seems to be basically a wash, and may actually be a slight regression overall depending on your codebase. (Again, this is why it's important to actually measure on your own codebase, on the browsers you actually target!)

In the case of Chakra, Uglify-style IIFEs are actually already optimized, but using optimize-js doesn't hurt because a function preceded by '(' still goes into the fast path.

Benchmarks

These tests were run using a handful of popular libraries, wrapped in performance.now() measurements. Each test reported the median of 251 runs. optimize-js commit da51013 was tested. Minification was applied using uglifyjs -mc, Uglify 2.7.0.

You can also try a live version of the benchmark.

Chrome 55, Windows 10 RS1, Surfacebook i5

ScriptOriginalOptimizedImprovementMinifiedMin+OptimizedImprovement
Create React App55.39ms51.71ms6.64%26.12ms21.09ms19.26%
ImmutableJS11.61ms7.95ms31.50%8.50ms5.99ms29.55%
jQuery22.51ms16.62ms26.18%19.35ms16.10ms16.80%
Lodash20.88ms19.30ms7.57%20.47ms19.86ms3.00%
PouchDB43.75ms20.36ms53.45%36.40ms18.78ms48.43%
ThreeJS71.04ms72.98ms-2.73%54.99ms39.59ms28.00%

Overall improvement: 20.63%

Edge 14, Windows 10 RS1, SurfaceBook i5

ScriptOriginalOptimizedImprovementMinifiedMin+OptimizedImprovement
Create React App32.46ms24.85ms23.44%26.49ms20.39ms23.03%
ImmutableJS8.94ms6.19ms30.74%7.79ms5.41ms30.55%
jQuery22.56ms14.45ms35.94%16.62ms12.99ms21.81%
Lodash22.16ms21.48ms3.05%15.77ms15.46ms1.96%
PouchDB24.07ms21.22ms11.84%39.76ms52.86ms-32.98%
ThreeJS43.77ms39.99ms8.65%54.00ms36.57ms32.28%

Overall improvement: 13.52%

Firefox 50, Windows 10 RS1, Surfacebook i5

ScriptOriginalOptimizedImprovementMinifiedMin+OptimizedImprovement
Create React App33.56ms28.02ms16.50%24.71ms22.05ms10.76%
ImmutableJS6.52ms5.75ms11.80%4.96ms4.58ms7.47%
jQuery15.77ms13.97ms11.41%12.90ms12.15ms5.85%
Lodash17.08ms16.63ms2.64%13.11ms13.22ms-0.80%
PouchDB19.23ms16.77ms12.82%13.77ms12.89ms6.42%
ThreeJS38.33ms37.36ms2.53%33.01ms30.32ms8.16%

Overall improvement: 8.26%

Safari 10, macOS Sierra, 2013 MacBook Pro i5

ScriptOriginalOptimizedImprovementMinifiedMin+OptimizedImprovement
Create React App31.60ms31.60ms0.00%23.10ms23.50ms-1.73%
ImmutableJS5.70ms5.60ms1.75%4.50ms4.50ms0.00%
jQuery12.40ms12.60ms-1.61%10.80ms10.90ms-0.93%
Lodash14.70ms14.50ms1.36%11.10ms11.30ms-1.80%
PouchDB14.00ms14.20ms-1.43%11.70ms12.10ms-3.42%
ThreeJS35.60ms36.30ms-1.97%27.50ms27.70ms-0.73%

Overall improvement: -1.04%

Note that these results may vary based on your machine, how taxed your CPU is, gremlins, etc. I ran the full suite a few times on all browsers and found these numbers to be roughly representative. In our test suite, we use a median of 151 runs to reduce variability.

Plugins

See also

Thanks

Thanks to @krisselden, @bmaurer, and @pleath for explaining these concepts in the various GitHub issues. Thanks also to astexplorer, acorn, and magic-string for making the implementation so easy.

Thanks to Sasha Aickin for generous contributions to improving this library (especially in v1.0.3) and prodding me to improve the accuracy of the benchmarks.

Contributing

Build and run tests:

npm install
npm test

Run the benchmarks:

npm run benchmark # then open localhost:9090 in a browser

Test code coverage:

npm run coverage

Changelog

  • v1.0.3
    • Much more accurate benchmark (#37)
    • Browserify-specific fixes (#29, #36, #39)
    • Webpack-specific fixes (#7, #34)
  • v1.0.2
    • Use estree-walker to properly parse ES6 (#31)
  • v1.0.1:
    • Don't call process.exit(0) on success (#11)
  • v1.0.0
    • Initial release