为何编译器在N个字节边界上对齐N个字节数据类型? [英] Why does compiler align N byte data types on N byte boundaries?

查看:77
本文介绍了为何编译器在N个字节边界上对齐N个字节数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么编译器将int对齐在4个字节的边界上,将short对齐在2个字节的边界上,将char对齐在1个字节的边界上. 我了解如果处理器的数据总线宽度为4字节,则需要2个内存读取周期才能从地址(不是4的倍数)读取int. 那么,为什么编译器不将所有数据对齐4个字节边界? 例如:

I don't understand why the compiler aligns int on 4 byte boundaries, short on 2 byte boundaries and char on 1 byte boundaries. I understand that the if the data bus width of the processor is 4 bytes, it takes 2 memory read cycles for reading an int from an address not a multiple of 4.
So, why doesn't the compiler align all data on 4 byte boundaries? For eg.:

struct s {
 char c;
 short s;
};

在这里, 1)为什么编译器在2个字节的边界上短对齐?假设处理器可以在一个内存读取周期中获取4个字节,那么即使在char和short之间没有填充,在上述情况下读取short也不用一个内存读取周期吗?

Here, 1) why does the compiler align short on a 2 byte boundary? Assuming that the processor can fetch 4 bytes on a single memory read cycle, wouldn't it take only 1 memory read cycle to read short in the above case even if there is no padding between char and short?

2)为什么编译器在4字节边界上不对齐?

2) Why doesn't the compiler align short on a 4 byte boundary?

推荐答案

我认为我找到了问题的答案. 为什么在char和short之间而不是在short之后填充字节可能有两个原因.

I think I found the answer to my question. There might be two reasons for why the byte is padded between char and short and not after short.

1)某些体系结构可能具有2字节的指令,这些指令仅从内存中获取2字节.如果是这种情况,则需要2个内存读取周期来提取该短数据.

1) Some architectures might have 2 byte instructions that fetch only 2 bytes from the memory. If such is the case, 2 memory read cycles are required to fetch the short.

2)某些体系结构可能没有2字节指令.即使在这种情况下,处理器也会从内存中获取4个字节到寄存器,并屏蔽不需要的字节以获取short值.如果未在char和short之间填充字节,则处理器必须移位字节才能获取short值.

2) Some architecture might not have 2 byte instructions. Even in that case, the processor fetches the 4 bytes from memory to the register and masks the unrequired bytes to get the short value. If the byte is not padded between char and short, the processor has to shift the bytes in order to get the short value.

以上两种情况均可能导致性能降低.这就是为什么短字节是2字节对齐的原因.

Both the above cases might result in slower performance. That is why the byte short is 2 byte aligned.

这篇关于为何编译器在N个字节边界上对齐N个字节数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆