Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefit of using short instead of int in for... loop

is there any benefit to using short instead of int in a for loop? i.e.

for(short j = 0; j < 5; j++) {

99% of my loops involve numbers below 3000, so I was thinking ints would be a waste of bytes. Thanks!

like image 530
Matthias D Avatar asked Jun 07 '11 18:06

Matthias D


People also ask

Should I use short instead of int?

Using short can conserve memory if it is narrower than int , which can be important when using a large array. Your program will use more memory in a 32-bit int system compared to a 16-bit int system.

Is short more efficient than int?

A CPU works more efficient when the data with equals to the native CPU register width. This applies indirect to . NET code as well. In most cases using int in a loop is more efficient than using short.

What is the difference between short and int?

short and int must be at least 16 bits, long must be at least 32 bits, and that short is no longer than int, which is no longer than long. Typically, short is 16 bits, long is 32 bits, and int is either 16 or 32 bits.

Is it better to use byte instead of int?

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.


2 Answers

No, there is no benefit. The short will probably end up taking a full register (which is 32 bits, an int) anyway.

You will lose hours typing the extra two letters in the IDE, too. (That was a joke).

like image 186
John Leehey Avatar answered Sep 25 '22 02:09

John Leehey


No. The loop variable will likely be allocated to a register, so it will end up taking up the same amount of space regardless.

like image 24
hammar Avatar answered Sep 26 '22 02:09

hammar