While reading the JVM specification (as one does), I was very surprised when I came across the 7 iconst_<i>
opcodes. After all, there is only one byte to play with.
I very rarely write the literals for 2, 3, 4 or 5 in my code. I can understand why -1, 0 and 1 might be treated specially, but it seems amazing to me that the designers would want to blow 4 precious opcodes on numbers that just happen to be quite small.
Does anyone know if there's a good reason for this? Am I underestimating the benefit of these?
I think, your assumption is correct: just to make the bytecode smaller and Java interpreter a tiny bit faster (there were no JIT compiler those times). Note that these bytecodes may be used much more often than you expect. For example, consider the following code:
Effectively it's compiled to something like:
So here
iconst_0
toiconst_4
are used even though you have no such constants in the source code.