如果内存是字节可寻址的,为什么我们需要对齐填充?
既然我们可以单独寻址内存的每个字节,为什么编译器要格外小心以确保结构及其成员与内存中的 32 位边界对齐? 我在这里可能是错的,但是在 32 位系统上,从 0x0800 开始获取 4 个字节是不是和从 0x0801 开始获取 4 个字节一样快?
Since we can address every byte of memory individually, why do compilers take extra care to make sure that structs and it's members align to 32-bit borders in memory?
I could be wrong here, but on a 32-bit system, is it not just as fast to get 4 bytes starting from say 0x0800, as it is from 0x0801?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在大多数架构上,对自然对齐的数据类型执行读/写速度更快。在某些系统上,如果您尝试访问某些未对齐的类型,则会生成异常(即大多数情况下崩溃)。因此,一般来说,除非您有充分的理由不这样做,否则您总是希望保持自然对齐。
另请参阅相关 SO 问题和解答:
内存对齐的目的
为什么数据结构对齐对性能很重要?
<一个href="https://stackoverflow.com/questions/1496848/does-unaligned-memory-access-always-cause-bus-errors">未对齐的内存访问是否总是会导致总线错误?
On most architectures it is faster to perform read/write on naturally aligned data types. On some systems it will generate an exception (i.e. crash in most cases) if you try to access certain types when they are misaligned. So in general you always want to maintain natural alignment unless you have a very good reason not to.
See also related SO questions and answers:
Purpose of memory alignment
why is data structure alignment important for performance?
Does unaligned memory access always cause bus errors?
摘自维基百科:
内存必须是
4 字节的倍数
,以便更快地访问并减少计算
为了更好的性能
。因此,如果内存是地址字节可寻址的,在大多数情况下通常是 4 字节块,那么我们知道下一个地址将从哪里开始,例如如上所述,如果您最终得到 14 字节(应该为 16 字节 4*4 = 16) 那么您就知道必须使用多少填充
16-14 = 2 字节填充
。这就是为什么在未对齐的内存中使用填充的原因。Taken from wikipedia:
The memory has to be
multiple of 4 bytes
for faster access and toreduce computation
forbetter performance
.so if the memory is address byte addressable usually of 4 bytes chunks in most of cases then we know where the next address is going to start e.g. as explained above also if you end up with
14 bytes
(that should be 16 bytes 4*4 = 16) then you know how much padding you have to use16-14 = 2 bytes padding
. that is why padding is used in misaligned memory.