java short,integer,long performance

bob picture bob · Mar 4, 2010 · Viewed 18k times · Source

I read that JVM stores internally short, integer and long as 4 bytes. I read it from an article from the year 2000, so I don't know how true it is now.

For the newer JVMs, is there any performance gain in using short over integer/long? And did that part of the implementation has changed since 2000?

Thanks

Answer

Olivier Croisier picture Olivier Croisier · Mar 4, 2010

Integer types are stored in many bytes, depending on the exact type :

  • byte on 8 bits
  • short on 16 bits, signed
  • int on 32 bits, signed
  • long on 64 bits, signed

See the spec here.

As for performance, it depends on what you're doing with them. For example, if you're assigning a literal value to a byte or short, they will be upscaled to int because literal values are considered as ints by default.

byte b = 10;  // upscaled to int, because "10" is an int

That's why you can't do :

byte b = 10;
b = b + 1;  // Error, right member converted to int, cannot be reassigned to byte without a cast.

So, if you plan to use bytes or shorts to perform some looping, you won't gain anything.

for (byte b=0; b<10; b++) 
{ ... } 

On the other hand, if you're using arrays of bytes or shorts to store some data, you will obviously benefit from their reduced size.

byte[] bytes = new byte[1000];
int[] ints = new int[1000];  // 4X the size

So, my answer is : it depends :)