Optimizing Code

Generally you should first compile and run your code without optimizations, which is the default when you just run emcc without specifying an optimization level. Such unoptimized builds contain some checks and assertions that can be very helpful in making sure that your code runs correctly. Once it does, it is highly recommended to optimize the builds that you ship, for several reasons: First, optimized builds are much smaller and faster, so they load quickly and run more smoothly, and second, un-optimized builds contain debug information such as the names of files and functions, code comments in JavaScript, etc. (which aside from increasing size may also contain things you do not want to ship to your users).

The rest of this page explains how to optimize your code.

How to optimize code

Code is optimized by specifying optimization flags when running emcc. The levels include: -O0 (no optimization), -O1, -O2, -Os, -Oz, -Og, and -O3.

For example, to compile with optimization level -O2:

emcc -O2 file.cpp

The higher optimization levels introduce progressively more aggressive optimization, resulting in improved performance and code size at the cost of increased compilation time. The levels can also highlight different issues related to undefined behavior in code.

The optimization level you should use depends mostly on the current stage of development:

  • When first porting code, run emcc on your code using the default settings (without optimization). Check that your code works and debug and fix any issues before continuing.

  • Build with lower optimization levels during development for a shorter compile/test iteration cycle (-O0 or -O1).