Why does the JVM have the iconst_2 - iconst_5 codes?

While reading the JVM specification (how this is done), I was very surprised when I came across the code codes for iconst_<i> 7. In the end, there is only one byte.

I very rarely write literals for 2, 3, 4, or 5 in my code. I can understand why -1, 0 and 1 can be considered on purpose, but it seems surprising to me that the designers would like to put 4 precious codes on numbers that are simply quite small.

Does anyone know if there is a good reason for this? Do I underestimate their benefits?

+5
source share
2 answers

I think your assumption is correct: just to reduce the bytecode and the Java interpreter a little faster (there was no JIT compiler at the time). Please note that these bytecodes can be used much more often than you expect. For example, consider the following code:

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

In fact, it compiled something like this:

 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 if you do not have such constants in the source code.

+4
source

Hope this can clarify your question. Why spend 4 Opcode.

See the byte code of this code.

 public static void main(String[] args) { int b = 20; int c = 5; int d= 6; } 

part of byte code

 0: bipush 20 2: istore_1 3: iconst_5 4: istore_2 5: bipush 6 7: istore_3 

As you can see for numbers greater than 5, it starts using bipush , which are usually less efficient than the equivalent iconst_<n> , and also occupy more bytes in the class file.

bipush byte1 extends byte1 to int and then pushes it onto the stack, because each slot in the Java stack is 32 bits wide (JVMs are stack-based virtual machines)

And to make sure bipush takes up more bytes ..

See the class file size from the following two codes. (This size is on my 64-bit computer .. it may differ on your computer, but the difference will be the same)

 public class Test2 { public static void main(String[] args) { int b = 5; } } 

size 406 bytes

now if i replaced b =6 ; the size of the same class file becomes 407 bytes , which remains constant as long as b=127 , which also uses bipush . This size difference is due to the fact that bipush has 2 bytes, one byte operation code, the second byte instantaneous constant value

bipush format:

 bipush byte 

as you can see from line 5: bipush 6 in the bytecode, while iconst_<n> uses only 1 byte.

Thus, such byte codes are defined for some frequently advanced numbers in order to increase the efficiency of the byte code execution and reduce the size of the byte code streams.

and, as Tagir said, these numbers will be used more often than you think.

+3
source

All Articles