Skip to content
kripken edited this page Feb 19, 2013 · 70 revisions

Optimizing the Generated Code

By default Emscripten will compile code in a fairly safe way, and without all the possible optimizations. You should generally try this first, to see if things work properly (if not, see the Debugging page). Afterwards, you may want to compile your code so it runs faster. This page explains how.

Note: You can also optimize the source code you are compiling into JavaScript, see Optimizing the source code.

Using emcc

The recommended way to optimize code is with emcc. emcc works like gcc, and basic usage is presented in the Emscripten Tutorial. As mentioned there, you can use emcc to optimize, for example

  emcc -O2 file.cpp

To see what the different optimizations levels do, run

  emcc --help
  • Optimization only makes sense when generating JavaScript, not when compiling to intermediate bitcode, and for that reason optimization flags are ignored unless the command will generate JavaScript. For more details see Building Projects.
  • The meaning of -O1, -O2 etc. in emcc are not identical to gcc, even though they have been chosen to be as familiar as possible! They can't be, because optimizing JavaScript is very different than optimizing native code. See the --help as mentioned before for details.
  • If you compile several files into a single JavaScript output, be sure to specify optimization during the last emcc invocation, where you transform the code into JavaScript. See Building Projects for details.

Viewing code optimization passes

If you run emcc with EMCC_DEBUG=1 (so, something like EMCC_DEBUG emcc), then it will output all the intermediate steps after each optimization pass. The output will be in TEMP_DIR/emscripten_temp, where TEMP_DIR is by default /tmp (and can be modified in ~/.emscripten). EMCC_DEBUG=2 will output even more information, a separate file will be saved for each JS optimization pass.

How to optimize code

The following procedure is how you should normally optimize your code:

  • First, run emcc on your code without optimization. The default settings are set to be safe. Check that your code works (if not, see the Debugging page) before continuing.
  • Build with -O2. That uses only safe optimizations, and should give good speed in most cases. If this is fast enough for you, you can stop here. If you must have all possible speed, continue.
  • Optionally, try -O3. If that works, great, but generally it will not, since it does some unsafe optimizations that can break code. If the code breaks, look in emcc --help under -O3 for the settings it changes, you can try to compile with -O2 plus each of those separately to see which will work.

Advanced Optimization Issues

Exception Catching

In -O1 and above exception catching is disabled. This prevents the generation of try-catch blocks, which lets the code run much faster. To re-enable them, run emcc with -s DISABLE_EXCEPTION_CATCHING=0.