byte/short Vs int as for loop counter variable

It is more likely to be confusing than helpful. Most developers expect to see an int value and you only have 32-bit or 64-bit registers in your CPU so it won't change how your program works or performs.

There are many options which work and are not harmful to your program but you need to think about the poor developer who has to read it and understand it later, this could be you 6 months from now. ;)

It is also not worth making such a change even if the performance were faster unless it was dramatically faster. Consider this change.

for (byte i = 1; i <= 120; i++)

or

for (byte i = 1; i <= x; i++)

You might thing this is fine as 200 < 2^8 and it compiles just fine, but it's actually an infinite loop.

You have to ask the question; How much faster does it have to be, if you increase the risk of introducing a bug later?

Usually the answer is it has to make my whole program significantly faster in a way I have measured (not just the bit you change) AND I have to need it to be significantly faster.


When you perform some operations on short or byte variable you have to explicitly typecast it back to the required type in java. So it is preferred to use int in place of byte and short. Example :

short s = 0;
s= (short) (s+10);

If you do not typecast it to int it will throw compile time error : Type mismatch: cannot convert from int to short So it is preferred to use int.


Short answer: No.

Long answer: No, because CPU's are optimized for integer operations. If you work with bytes or shorts, the CPU constantly has to convert it to integers and back, generally by applying bitmasks.

Tags:

Java

For Loop