Search code examples
javajvmopcodes

Why does the JVM have the iconst_2 - iconst_5 opcodes?


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?


Solution

  • 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:

    int[] a = {10, 20, 30, 40};
    

    Effectively it's compiled to something like:

    int[] a = new int[4];
    a[0] = 10;
    a[1] = 20;
    a[2] = 30;
    a[3] = 40;
    

    So here iconst_0 to iconst_4 are used even though you have no such constants in the source code.