首页 > 解决方案 > 为什么 Go 经常将字符串的数据存储在未对齐的地址

问题描述

我已经阅读了很多关于内存中值对齐的重要性的内容,因为访问未对齐的地址可能会减慢操作速度,或者根本不工作,具体取决于 CPU 架构(参考https://syslog.ravelin.com/ go-and-memory-layout-6ef30c730d51)。但后来我注意到,在 Go 中实例化一个简单的字符串时,它经常将字符串值存储在未对齐的地址中。

这可以通过运行以下代码看到:

package main

import (
    "fmt"
    "unsafe"
    "reflect"
)

func main() {
    testString:= "testString"

    fmt.Println(fmt.Sprintf("Data is at address %d", ((*reflect.StringHeader)(unsafe.Pointer(&testString))).Data))
}

https://play.golang.org/p/d1eX0nP3AgV上运行它时,我不断得到:

Data is at address 1140305

1140305显然不能被4or整除8

有人可以解释一下为什么 Go 将该值存储在一个未对齐的地址中吗?使用对齐的不是更好吗?这仅仅是为了不浪费空间,同时依靠现代 CPU 可以处理它的事实。或者是因为虚拟内存层抽象了物理内存地址,实际上物理地址是正确对齐的?

标签: gomemory-managementmemory-layout

解决方案


您是对的,32 位值(例如整数)应该在 4 字节边界上对齐,否则访问它可能需要两次内存访问而不是一次。类似地,64 位值应该在 8 字节边界上对齐,尽管在 32 位系统(即 32 条数据线到内存)中,4 字节边界就足够了,因为无论如何都需要两次内存访问。

However, the data of a string in Go is effectively an array of bytes and hence has no alignment requirements. You will find the same thing if you print the address of a string in C (which cares a lot about alignment for efficiency reasons).

Alignment is fairly straightforward once you understand it but takes a lot of explaining. I wrote about it (for C) at http://devmethodologies.blogspot.com/2013/04/alignment-and-pragma-pack.html.


推荐阅读