Primitives competition (2)

1 February 2016

In previous post about primitives I checked how fast usual operations perform on different types of integral primitives. Initially I thought that one post on allocation space would be enough but after doing some research I realised that there is enough room for two. In this one I will write about allocation on stack frame during method calls.

I didn’t have experience on doing this kind of investigation so I searched about information on this subject. I found a very good post about JVM Internals written by James D Bloom and I used it to understand what I have to do.

One of the situations in which we use integral primitives is when we declare and initialize them as local variables and then do some calculations.
I prepared a simple example that looks like the one below:

1

2

3

4

5

6

7

8

9

10

11

12

13

packagecom.espressoprogrammer.competition.primitives.stack;

publicclassByteFields{

publicstaticvoidmain(String...args){

bytevalue1=10;

bytevalue2=20;

byteresult=(byte)(value1+value2);

}

}

In the same package I created similar classes for the other integral primitives and I uploaded them on github. In order to see how this code is compiled into bytecode I used

The complete bytecode for this class and for the other classes can be checked on github. The first thing I noticed is that bytecode for byte, short and int examples is almost identical. The only exception is on line 9 which casts from int to byte and short. Bytecode instructions use operand stack to perform our simple sum operation and in this case it is easy to understand them:

lines 0: and 2: initialize value1

lines 3: and 5: initialize value2

lines 6: 7: and 8: perform the sum

line 9 casts int result in byte

line 10 stores the result in result variable

LocalVariableTable is also almost identical for byte, short and int and it is because these types need one slot (4 bytes) and long needs two slots (8 bytes).

My conclusion is that for local variables there isn’t a real difference between byte, short and int. All instances occupy the same space (4 bytes) and the operations are the same.