Search code examples
javavariablesmathprocessor

Processor usage when using byte and short data types in Java


I read the following in Starting out with Java. from control structures through data structures - 3rd edition by Tony Gaddis on page 67:

When values of the byte or short data types are used in arithmetic expressions, they are temporarily converted to int values.

This is referring to Java.

I was wondering if doing mathematical operations using byte or short data types, although they save memory, increases the processor usage due to the conversion to the int data type, as opposed to just using int data types.

For example:

Does this:

byte x = 2;
byte y = 3;
int z = x + y;

use more of the processor than this:

int x = 2;
int y = 3;
int z = x + y;

I understand that the first example uses less memory. And I also understand that the difference in processor usage, if any, would be very slight.


Solution

  • In order to do computation (like x+y), processor need to load both x and y in registers (depends on architecture, but at least on of x or y should be in registers). Registers have size of 32 or 64 bits (at least on platforms where Java can be used). So, this values are anyways are converted to 32(64) bit integer. It is done automatically and does not consume additional CPU resources. So computational speed will be the same.