"in java, is it more efficient to use byte or short instead of int and float instead of double?" Code Answer


am i wrong in assuming it should be faster and more efficient? i'd hate to go through and change everything in a massive program to find out i wasted my time.

short answer

yes, you are wrong. in most cases, it makes little difference in terms of space used.

it is not worth trying to optimize this ... unless you have clear evidence that optimization is needed. and if you do need to optimize memory usage of object fields in particular, you will probably need to take other (more effective) measures.

longer answer

the java virtual machine models stacks and object fields using offsets that are (in effect) multiples of a 32 bit primitive cell size. so when you declare a local variable or object field as (say) a byte, the variable / field will be stored in a 32 bit cell, just like an int.

there are two exceptions to this:

  • long and double values require 2 primitive 32-bit cells
  • arrays of primitive types are represent in packed form, so that (for example) an array of bytes hold 4 bytes per 32bit word.

so it might be worth optimizing use of long and double ... and large arrays of primitives. but in general no.

in theory, a jit might be able to optimize this, but in practice i've never heard of a jit that does. one impediment is that the jit typically cannot run until after there instances of the class being compiled have been created. if the jit optimized the memory layout, you could have two (or more) "flavors" of object of the same class ... and that would present huge difficulties.


looking at the benchmark results in @meriton's answer, it appears that using short and byte instead of int incurs a performance penalty for multiplication. indeed, if you consider the operations in isolation, the penalty is significant. (you shouldn't consider them in isolation ... but that's another topic.)

i think the explanation is that jit is probably doing the multiplications using 32bit multiply instructions in each case. but in the byte and short case, it executes extra instructions to convert the intermediate 32 bit value to a byte or short in each loop iteration. (in theory, that conversion could be done once at the end of the loop ... but i doubt that the optimizer would be able to figure that out.)

anyway, this does point to another problem with switching to short and byte as an optimization. it could make performance worse ... in an algorithm that is arithmetic and compute intensive.

By Shane Voisard on February 26 2022

Answers related to “in java, is it more efficient to use byte or short instead of int and float instead of double?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.