Would it make a difference to use short here instead of int?Code:const short REPEATS = 10;
for(short i=0; i<REPEATS; i++)
{
std::cout<< "...\n";
}
Printable View
Would it make a difference to use short here instead of int?Code:const short REPEATS = 10;
for(short i=0; i<REPEATS; i++)
{
std::cout<< "...\n";
}
If a short is half the size of int in terms of memory allocated, wouldn't you be (however minor) saving memory by using short any time you can as in the example? Can someone explain in detail? I do not ever recall seeing a short used in a loop like this, and I would like to understand why. Ty.
Maybe, but promotion to int will be performed anyway due to the arithmetic, so it may not make a difference in the end.Quote:
Originally Posted by QuestionKing
And it's possible that short will be slower than int, though I don't think that's the case on x86.
"int" is defined to be the "natural" word size of the machine, usually meaning it's the fastest, and should be used for everything "general purpose", like iterators.
Only use other sizes if you have a good reason to. Eg, if you need an array of a few GBs, or if you need to store something bigger than the size of int can hold.
For that example you also could have used a char instead of a short or int and saved even more space, but like laserlight said, it would probably lose that space advantage because of a promotion to int.
this decision should be made only after profiling. Good profiler could tell you if the code slowness is caused by the cache misses and so you would like to shorten the types used.
If you do not have performance problems or you have not run profiler or profiler has not found such types of problems in the code - no premature optimization should be done
Do you really lose the space advantage though?
It will make a copy of the value into an int size container for math operations explicitly, but not convert the array of chars in to an array of ints in memory, right?
If the system converts the source array in memory to int what was the point of even specifying a datatype, everything might as well be ints. xD
Am I confused about something?
Only if you want to burden the maintainer with needing to remember to change the data type if he/she ever wants to change REPEATS to some value larger than a short could hold.
At any rate, since REPEATS is a small constant, the compiler might unroll the loop anyway.
Another concern is that the value is signed. I suggest that normally, loop counters and array indices should be unsigned.
Loop induction variables are nearly always promoted to a register, so you don't save any memory there anyway. In general, if you don't have an array of at least 500 elements, worrying about the data type is rather useless. And even then you'll still want to profile first.