- Notifications
You must be signed in to change notification settings - Fork103
Optimize a JS file for faster parsing (UNMAINTAINED)
License
nolanlawson/optimize-js
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Optimize a JavaScript file for faster initial execution and parsing, by wrapping all immediately-invoked functions or likely-to-be-invoked functions in parentheses.
Update The V8 team wrotea blog post about why you probably shouldn't use optimize-js anymore.
npm install -g optimize-js
optimize-js input.js > output.js
Example input:
!function(){}()functionrunIt(fun){fun()}runIt(function(){})
Example output:
!(function(){})()functionrunIt(fun){fun()}runIt((function(){}))
Browser | Typical speed boost/regression using optimize-js |
---|---|
Chrome 55 | 20.63% |
Edge 14 | 13.52% |
Firefox 50 | 8.26% |
Safari 10 | -1.04% |
These numbers are based on a benchmark of common JS libraries. For benchmark details, seebenchmarks.
To test on your own JavaScript bundle, check outtest-optimize-js.
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
varoptimizeJs=require('optimize-js');varinput="!function() {console.log('wrap me!')}";varoutput=optimizeJs(input);// "!(function() {console.log('wrap me!')})()"
You can also pass in arguments:
varoptimizeJs=require('optimize-js');varinput="!function() {console.log('wrap me!')}";varoutput=optimizeJs(input,{sourceMap:true});// now the output has source maps
Modern JavaScript engines like V8, Chakra, and SpiderMonkey have a heuristic where they pre-parse mostfunctions 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 neverexecuted or are lazily executed.So a pre-parse can prevent a slower startup time by only checking for what the browser absolutely needsto 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 afurther 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 parseravoids 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 includecommon module formats like UMD/Browserify/Webpack/etc.), the browser will actually parse the functiontwice, first as a pre-parse and secondas 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 byparsing the entire JavaScript file in advance (a luxury the browser can't afford) and inserting parentheses in the cases where weknowthe function will be immediately executed (or where we have a good hunch). That's whatoptimize-js
does.
More details on the IIFE optimization can be found inthis discussion. Some of my thoughts on the virtues of compile-time optimizations can be found inthis post.
The current implementation is to parse to a syntax tree and check for functions that:
- Are immediately-invoked via any kind of call statement (
function(){}()
,!function(){}()
, etc.) - 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 tendsto 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.
Yes,optimize-js
might add as many as two bytes (horror!) per function, which amounts to practically nil once youtake gzip into account. To prove it, here are the gzipped sizes for the libraries I use in the benchmark:
Script | Size (bytes) | Difference (bytes) |
---|---|---|
benchmarks/create-react-app.min.js | 160387 | |
benchmarks/create-react-app.min.optimized.js | 160824 | + 437 |
benchmarks/immutable.min.js | 56738 | |
benchmarks/immutable.min.optimized.js | 56933 | + 195 |
benchmarks/jquery.min.js | 86808 | |
benchmarks/jquery.min.optimized.js | 87109 | + 301 |
benchmarks/lodash.min.js | 71381 | |
benchmarks/lodash.min.optimized.js | 71644 | + 263 |
benchmarks/pouchdb.min.js | 140332 | |
benchmarks/pouchdb.min.optimized.js | 141231 | + 899 |
benchmarks/three.min.js | 486996 | |
benchmarks/three.min.optimized.js | 487279 | + 283 |
Sure! If you are already shipping a bundled, minified version of your library, then there's no reason not to applyoptimize-js
(assuming you benchmark your code to ensure it does indeed help!). However, note thatoptimize-js
should runafter Uglify, since Uglify strips extra parentheses and alsonegates IIFEs by default. This also means that if your users apply Uglification to your bundle, then the optimization will be undone.
Also note that becauseoptimize-js
optimizes for some patterns that are based on heuristics rather thanknown eagerly-invokedfunctions, it may actually hurt your performance in some cases. (See benchmarks below for examples.) Be sure to check thatoptimize-js
is a help rather than a hindrance for your particular codebase, using something like:
<script>varstart=performance.now();</script><scriptsrc="myscript.js"></script><script>varend=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 inour benchmarks.
You may also want to check outmarky,which allows you to easily set mark/measure points that you can visually inspect in the Dev Tools timeline to ensure that the fullcompile time is being measured.
Also, be sure to test in multiple browsers! If you need an Edge VM, check outedge.ms.
Possibly! This is a free and open-source library, so I encourage anybody to borrow the code or the good ideas. :)
As described above, the pre-parsing optimization in browsers is a very good idea for the vast majority of the web, where most functionsaren't immediately executed. However, sinceoptimize-js
knows when your functions are immediately executed (or can make reasonableguesses), it can be more judicious in applying the paren hack.
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 usingoptimize-js
doesn't hurt because afunction preceded by'('
still goes into the fast path.
These tests were run using a handful of popular libraries, wrapped inperformance.now()
measurements. Each test reported the median of 251 runs.optimize-js
commitda51013 was tested. Minification was applied usinguglifyjs -mc
, Uglify 2.7.0.
You can also trya live version of the benchmark.
Script | Original | Optimized | Improvement | Minified | Min+Optimized | Improvement |
---|---|---|---|---|---|---|
Create React App | 55.39ms | 51.71ms | 6.64% | 26.12ms | 21.09ms | 19.26% |
ImmutableJS | 11.61ms | 7.95ms | 31.50% | 8.50ms | 5.99ms | 29.55% |
jQuery | 22.51ms | 16.62ms | 26.18% | 19.35ms | 16.10ms | 16.80% |
Lodash | 20.88ms | 19.30ms | 7.57% | 20.47ms | 19.86ms | 3.00% |
PouchDB | 43.75ms | 20.36ms | 53.45% | 36.40ms | 18.78ms | 48.43% |
ThreeJS | 71.04ms | 72.98ms | -2.73% | 54.99ms | 39.59ms | 28.00% |
Overall improvement:20.63% |
Script | Original | Optimized | Improvement | Minified | Min+Optimized | Improvement |
---|---|---|---|---|---|---|
Create React App | 32.46ms | 24.85ms | 23.44% | 26.49ms | 20.39ms | 23.03% |
ImmutableJS | 8.94ms | 6.19ms | 30.74% | 7.79ms | 5.41ms | 30.55% |
jQuery | 22.56ms | 14.45ms | 35.94% | 16.62ms | 12.99ms | 21.81% |
Lodash | 22.16ms | 21.48ms | 3.05% | 15.77ms | 15.46ms | 1.96% |
PouchDB | 24.07ms | 21.22ms | 11.84% | 39.76ms | 52.86ms | -32.98% |
ThreeJS | 43.77ms | 39.99ms | 8.65% | 54.00ms | 36.57ms | 32.28% |
Overall improvement:13.52% |
Script | Original | Optimized | Improvement | Minified | Min+Optimized | Improvement |
---|---|---|---|---|---|---|
Create React App | 33.56ms | 28.02ms | 16.50% | 24.71ms | 22.05ms | 10.76% |
ImmutableJS | 6.52ms | 5.75ms | 11.80% | 4.96ms | 4.58ms | 7.47% |
jQuery | 15.77ms | 13.97ms | 11.41% | 12.90ms | 12.15ms | 5.85% |
Lodash | 17.08ms | 16.63ms | 2.64% | 13.11ms | 13.22ms | -0.80% |
PouchDB | 19.23ms | 16.77ms | 12.82% | 13.77ms | 12.89ms | 6.42% |
ThreeJS | 38.33ms | 37.36ms | 2.53% | 33.01ms | 30.32ms | 8.16% |
Overall improvement:8.26% |
Script | Original | Optimized | Improvement | Minified | Min+Optimized | Improvement |
---|---|---|---|---|---|---|
Create React App | 31.60ms | 31.60ms | 0.00% | 23.10ms | 23.50ms | -1.73% |
ImmutableJS | 5.70ms | 5.60ms | 1.75% | 4.50ms | 4.50ms | 0.00% |
jQuery | 12.40ms | 12.60ms | -1.61% | 10.80ms | 10.90ms | -0.93% |
Lodash | 14.70ms | 14.50ms | 1.36% | 11.10ms | 11.30ms | -1.80% |
PouchDB | 14.00ms | 14.20ms | -1.43% | 11.70ms | 12.10ms | -3.42% |
ThreeJS | 35.60ms | 36.30ms | -1.97% | 27.50ms | 27.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.
Thanks to@krisselden,@bmaurer, and@pleath for explaining these concepts in the various GitHub issues. Thanks also toastexplorer,acorn, andmagic-string for making the implementation so easy.
Thanks toSasha Aickin for generous contributions to improving this library (especially in v1.0.3)and prodding me to improve the accuracy of the benchmarks.
Build and run tests:
npm installnpmtest
Run the benchmarks:
npm run benchmark# then open localhost:9090 in a browser
Test code coverage:
npm run coverage
About
Optimize a JS file for faster parsing (UNMAINTAINED)