IT lexicon › Programming › Loop fusion

Loop fusion

Programming På svenska → Updated: 2026-11-05

Two adjacent loops over the same range are merged into one, so data written by the first is still in cache when the second reads it.

If one loop computes b[i] = a[i] * 2 and the next c[i] = b[i] + 1, a large array b has long left the cache by the time it's needed again. After fusion both steps happen in the same iteration, and sometimes the intermediate array disappears entirely. It's only legal if no iteration of the second loop needs a value the first hasn't produced yet — dependence analysis decides.

The idea is old Fortran lore but has found a second career in machine learning under the name kernel fusion: XLA, TorchInductor and friends merge element-wise operations so the GPU doesn't write intermediate results back to memory. NumPy doesn't, which is why a long NumPy expression allocates a temporary array per operator.

← Back to the lexicon