如果内存是字节可寻址的,为什么还要有对齐填充? [英] Why do we have alignment padding if memory is byte-addressable?

查看:88
本文介绍了如果内存是字节可寻址的,为什么还要有对齐填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我们可以分别寻址内存的每个字节,为什么编译器要格外小心以确保结构及其成员与内存中的32位边界对齐? 我在这里可能是错的,但是在32位系统上,从0x0800开始和从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?

推荐答案

在大多数体系结构上,对自然对齐的数据类型执行读/写操作更快.在某些系统上,如果您尝试在某些类型未对齐时尝试访问某些类型,它将生成一个异常(即在大多数情况下为 crash ).因此,总的来说,除非您有充分的理由不这样做,否则您总是希望保持自然对齐.

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.

另请参阅相关的SO问题和答案:

See also related SO questions and answers:

为什么数据结构对齐对性能很重要?

未对齐的内存访问是否总是会导致总线错误? /a>

Does unaligned memory access always cause bus errors?

这篇关于如果内存是字节可寻址的,为什么还要有对齐填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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