简体   繁体   English

32位架构(GCC)上的8位int与32位int

[英]8 bit int vs 32 bit int on a 32 bit architechture (GCC)

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) uint8而不是int因为i只需要达到32)

This would make sense when coding on an 8bit microprocessor. 在8位微处理器上编码时这是有意义的。 However, am I saving any resources if running this code on a 32bit microprocessor (where int might be 16 or 32 bit)? 但是,如果在32位微处理器( int可能是16位或32位)上运行此代码,我是否可以保存任何资源? Does a compiler like GCC do any magic/juju underneath when I explicitly use an 8bit int on a 32bit architecture? 当我在32位架构上明确使用8位int时,像GCC这样的编译器是否会在下面执行任何魔术/ juju?

In most cases, there won't be any memory usage difference because i will never be in memory. 在大多数情况下,不会有任何内存使用差异,因为i永远不会在内存中。 i will be stored in a CPU register, and you can't really use one register to store two variables. i将存储在CPU寄存器中,你不能真正使用一个寄存器来存储两个变量。 So i will take one register, uint8 or uint32 doesn't matter. 所以i会拿一个寄存器, uint8uint32并不重要。

In some rare cases, i will actually be stored in memory, because the loop is so big that all the CPU registers are taken. 在极少数情况下, i实际上会存储在内存中,因为循环非常大,所以所有CPU寄存器都被占用。 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. 在这种情况下,你很可能也不会获得任何内存,因为其他多字节变量将被对齐,然后i会跟着一些无用的填充字节来对齐下一个变量。

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. 现在,如果i实际上存储在内存中,并且还有其他8位变量来填充填充,那么你可以节省一些内存,但是它太少而且不太可能,它可能不值得。 Performance-wise, the difference between 8-bit and 32-bit is very architecture dependent, but usually it will be the same. 性能方面,8位和32位之间的差异非常依赖于体系结构,但通常它们是相同的。

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). 此外,如果您在64位环境中工作,这种内存保存可能不存在,因为64位调用约定会在堆栈上强加一个16字节的大对齐(如果它在内存中, i将被存储) )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM