8 bit int vs 32 bit int in 32 bit architecture (GCC)

While coding, I try not to use more variable memory than necessary, and this forces me to write code like this:

for (uint8 i = 0; i < 32; i++) {
   ...
}

      

instead:

for (int i = 0; i < 32; i++) {
   ...
}

      

( uint8

instead of int

because i

you only need up to 32)

This makes sense when encoding on an 8-bit microprocessor. That said, am I saving any resources if you run this code on a 32-bit microprocessor (where int

might 16 or 32 bits be)? Does a compiler like GCC have any magic / juju underneath when I explicitly use 8bit int

on a 32bit architecture?

+3


source to share


1 answer


In most cases, there will be no difference in memory usage as it i

will never be in memory. i

will be stored in the CPU register and you cannot use one register to store two variables. Thus, it i

will take one register, uint8

or it uint32

doesn't matter.

In some rare cases, it i

will actually be stored in memory because the loop is so large that all the processor registers are taken. In this case, there is still a good chance you won't get any memory, because the other multibyte variables will be aligned, and i

followed by some useless padding bytes to align the next variable.



Now if i

actually stored in memory and other 8-bit variables are used to fill the padding, you might save some memory, but that's so small and unlikely that it probably isn't worth it. In terms of performance, the difference between 8-bit and 32-bit is very architecture dependent, but it will usually be the same.

Also, if you are running in a 64-bit environment, this memory retention probably doesn't exist, because in the 64-bit convention, a huge 16 byte alignment on the stack is imposed on the call (where it i

will be saved if it is in memory).

+4


source







All Articles