Hope this can Clarify your Question Why waste the 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 number greater 5 it's starts using bipush
which are typically less efficient than the equivalent iconst_<n>
and also take up more bytes in the class file.
bipush byte1
expands byte1
to an int and then pushes it onto the
stack, because every slot on the Java stack is 32 bits wide (JVM is Stack Based Virtual Machines)
And to see if bipush
takes up more byte ..
See the class file size of two following code.(This size are on my 64bit machine.. it may differ on your machine but the difference will be same)
public class Test2 {
public static void main(String[] args) {
int b = 5;
}
}
size 406 bytes
now if i replace b =6
;
the size of the same class file becomes 407 bytes
which remains constant till even when b=127
which also uses bipush
. This difference in Size is due to the fact that bipush has 2 bytes, one byte opcode, second byte immediate constat value
bipush format:
bipush
byte
as you can see from the line 5: bipush 6
in bytecode while iconst_<n>
uses 1 byte only.
So such bytecodes are defined for some commonly pushed numbers, to
increase the efficiency of bytecode execution and reduce the size of
bytecode streams.
and as Tagir said those numbers would be used more often than you would think