Does Julia optimize code automatically?

This is an optimization known as loop-invariant code motion (LICM), which as the name suggests tries to identify code that doesn’t change in the loop and move it out of the loop. Julia’s compiler (and LLVM) sometimes is able to perform this optimization, and newer versions of Julia get better at, but it’s not always reliably able to identify when it can apply it.

So generally it is a good idea to hoist the code out of the loop yourself, especially when it is a relatively expensive calculation.

BTW: Manual LICM in Julia has some interesting slides about how LICM can work in the language of the compiler.

See also Loops, allocations and helping the coder

6 Likes