1
Java / Re: ranges of ints, bytes, shorts, chars
« on: June 15, 2014, 12:09:35 PM »Unless you have arrays, the JVM won't make a difference handling short, byte or int. Local variables of these types all occupy 32 bit cells within the JVM despite their actual length.
The integer operations are optimized for int values. Using byte or short instead of int is most of the time less efficient as the operations are slower.
Memorywise it is really only a good choice if dealing with very large arrays.
In only remembered that it saves space in arrays so i concluded it would save space in variables too, which was wrong.
Regarding space and efficiency:
Code: [Select]
public int addInts(int x, int y) {
return x + y;
}
public short addShorts(short x, short y) {
// you need the (short) cast since short + short returns an int
return (short) (x + y);
}
which compiles to:
Code: [Select]
public int addInts(int x, int y) {
iload_1 //loads the int value of x on the stack
iload_2 //loads the int value of y on the stack
iadd //pops the two int values on top of the stack (here: x, y) and pushes the sum on the stack
ireturn //returns the int value on top of the stack
}
public short addShorts(short x, short y) {
iload_1 //loads the int value of x on the stack --> same space as an int in ram needed
iload_2 //loads the int value of y on the stack --> same space as an int in ram needed
iadd //pops the two int values on top of the stack (here: x, y) and pushes the sum on the stack
i2s // converts the int to short --> extra instruction -->less efficient
ireturn //returns the int (in this case it's a short) value on top of the stack
}
The reason why there are no extra instructions for datatypes like shorts is explained in the JVM specification:
Quote
Given the Java Virtual Machine's one-byte opcode size, encoding types into opcodes places pressure on the design of its instruction set. If each typed instruction supported all of the Java Virtual Machine's run-time data types, there would be more instructions than could be represented in a byte. Instead, the instruction set of the Java Virtual Machine provides a reduced level of type support for certain operations. In other words, the instruction set is intentionally not orthogonal. Separate instructions can be used to convert between unsupported and supported data types as necessary.In our example: there are no load, add and return instructions for shorts => the JVM uses the integer ones.
I hope this is more correct.