Alex Rivera | Logout

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

Asked 2011-06-07T18:47:01.843
10

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!

Edit
Report

4 Answers

13

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).

answered 2011-06-07T18:52:50.127
10

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

answered 2011-06-07T18:50:23.433
0

Nope. Chances are your counter will end up in a register anyway, and they are typically at least the same size as int

answered 2011-06-07T18:50:18.470
0

As most others have said, computationally there is no advantage and might be worse. However, if the loop variable is used in a computation requiring a short, then it might be justified:

for(short j = 0; j < 5; j++)
{
   // void myfunc(short arg1);
   myfunc(j);
}

All this really does is prevent a warning message as the value passed would be promoted to an int (depending on compiler, platform, and C++ dialect). But it looks cleaner, IMHO.

Certainly not worth obsessing over. If you are looking to optimize, remember the rules (forget who came up with these):

  1. Don't
  2. Failing Step 1, first Measure
  3. Make a change
  4. If bored, exit, else go to Step 2.
answered 2011-06-07T21:13:29.650

Your Answer