When you think about code optimisation, you might imagine complex analysis over entire programs, sophisticated JIT compilers, or elaborate data-flow analyses. But some of the most effective optimisations come from a much simpler technique: peephole optimisation. This approach can yield surprisingly good results with relatively little complexity.
Imagine looking at a piece of code through a small window – a peephole – that only shows you a few instructions at a time. As you slide this window over your code, you look for patterns that can be replaced with more efficient alternatives. Consider this simple Java code:
Clearly, the addition of zero to some other value is redundant and through our peephole, we can spot this pattern and remove it.
This optimisation is local – we only needed to look at a small sequence of instructions to identify and apply it. We didn’t need to analyse the entire program or understand complex control flow. This locality is what makes peephole optimisation both powerful and simple.