I remember reading somewhere that it is better to use integers as loop counter variables rather than char or short. If yes, why? Does it provide any optimization benefits?
Generally, the compiler will make int
to be a good size for putting into one of your CPU's general purpose registers. That generally leads to fast access.
Of course there's no guarantee of anything. The compiler is free to do a lot of things, including, I would guess, promote some of your code that uses char
to some larger type. So the difference might not even matter.
Really, for the answer that's true for your compiler, you should look at the assembly it outputs.
In 32-bit architecture operations with 4 bytes (int) variables are usually faster. This is mainly due to size of registers and memory alignment. In 64 bit architecture it int will (should) be automatically made 64-bit integer.
Alexey* is right, it's usually faster to use a type that's the same width as the architecture (i.e. an int32 for a 32 bit system)
Also, if you use a char i.e.
for(char i=0;i<max;++i)
there's a slight chance that you (or a colleague) will come back to the code in a month's time and change max to something high, causing an overflow and an annoying bug ;)
Sam
*and everyone else who answered while I was writing this!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With