# Does Julia optimize code automatically?

**URL:** https://discourse.julialang.org/t/does-julia-optimize-code-automatically/108913
**Category:** General Usage
**Tags:** question
**Created:** [January 17, 2024, 2:46pm UTC](https://discourse.julialang.org/t/does-julia-optimize-code-automatically/108913 "2024-01-17T14:46:53Z")
**Posts on this page:** 1
**Showing post:** 2

<div class="post-metadata">

### Author: ![ericphanson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ericphanson/32/215186_2.png) [@ericphanson](https://discourse.julialang.org/u/ericphanson)
#### Post date: [January 17, 2024, 3:00pm UTC](https://discourse.julialang.org/t/does-julia-optimize-code-automatically/108913/2 "2024-01-17T15:00:11Z")

</div>

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](https://vchuravy.dev/talks/licm/) has some interesting slides about how LICM can work in the language of the compiler.

See also [Loops, allocations and helping the coder](https://discourse.julialang.org/t/loops-allocations-and-helping-the-coder/104733)

---

_[View the full topic](https://discourse.julialang.org/t/does-julia-optimize-code-automatically/108913)._
