Peephole optimisation is a technique for code optimisation which considers only relatively small chunks of code at any one time. It can be used on a low-level representation of a program, assembly language or a low-level pseudo-code without having to understand the full context of the program. Simple rules are applied to transform one set of instructions into a different set which have the same effect but which are smaller or more efficient.
Many years ago I wrote a peephole optimiser for the Z80 code emitted by a Small C compiler. It used five passes to process the assembly language code and implemented the five passes in one program using coroutines. As the Small C compiler developed it expanded to fill the 64 Kbytes of memory available to the Z80. It was only with the aid of the peephole optimiser that the compiler was able to run at all: the unoptimised code was too big for the memory available.
Reading about the Java Virtual Machine caused me to wonder if it would be possible to use similar techniques to perform optimise Java bytecodes. Why would you want to do this? Possible advantages are:
In the following pages I describe the optimisations that I have spotted. I encourage you to examine your own disassembled code to see if you can find further opportunities for improvement. See the conclusion for details of how to report new optimisations.