While coding, I try not to use more variable memory than needed and that leads me to write code like this:
for (uint8 i = 0; i < 32; i++) {
...
}
instead of:
for (int i = 0; i < 32; i++) {
...
}
(uint8
instead of int
because i
only need to go up to 32)
This would make sense when coding on an 8bit microprocessor. However, am I saving any resources if running this code on a 32bit microprocessor (where int
might be 16 or 32 bit)? Does a compiler like GCC do any magic/juju underneath when I explicitly use an 8bit int
on a 32bit architecture?
In most cases, there won't be any memory usage difference because i
will never be in memory. i
will be stored in a CPU register, and you can't really use one register to store two variables. So i
will take one register, uint8
or uint32
doesn't matter.
In some rare cases, i
will actually be stored in memory, because the loop is so big that all the CPU registers are taken. In this case, there is still a good chance you won't gain any memory either, because others multi-bytes variables will be aligned, and i
will be followed by some useless padding bytes to align the next variable.
Now, if i
is actually stored in memory, and there are other 8-bit variables to fill the padding, you may save some memory, but it's so little and so unlikely that it probably isn't worth it. Performance-wise, the difference between 8-bit and 32-bit is very architecture dependent, but usually it will be the same.
Also, if you are working in a 64-bit environment, this memory saving is probably non-existent, because the 64-bit call convention impose a huge 16-bytes alignment on the stack (where i
will be stored if it is in memory).