登录
首页 >  Golang >  Go问答

是否可以在结构中使用填充项,如空格?

来源:stackoverflow

时间:2024-02-13 12:09:25 110浏览 收藏

golang学习网今天将给大家带来《是否可以在结构中使用填充项,如空格?》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!

问题内容

我正在玩go,并试图计算并获取结构对象的大小。如果您查看以下结构,会发现一些有趣的东西:

type something struct {
        aninteger        int16 // 2 bytes
        anotherint       int16 // 2 bytes
        yetanother       int16 // 2 bytes
        somebool         bool  // 1 byte
} // i expected 7 bytes total

type somethingbetter struct {
        aninteger        int16 // 2 bytes
        anotherint       int16 // 2 bytes
        yetanother       int16 // 2 bytes
        somebool         bool  // 1 byte
        anotherbool      bool  // 1 byte
} // i expected 8 bytes total

type nested struct {
        something // 7 bytes expected at first
        completingbyte   bool // 1 byte
} // 8 bytes expected at first sight

但是我使用 unsafe.sizeof(...) 得到的结果如下:

Something         -> 8 bytes
SomethingBetter   -> 8 bytes
Nested            -> 12 bytes, still, after finding out that "Something" used 8 bytes, though this might use 9 bytes

我怀疑 go 做了一些类似填充的事情,但我不知道它是如何以及为什么这样做的,有一些公式吗?还是逻辑?如果使用空格填充,它是随机完成的吗?或者基于一些规则?


正确答案


是的,我们有填充!如果您的系统架构是 32-bit,则字大小为 4 bytes;如果是 64-bit,则字大小为 8 bytes。现在,字的大小是多少? “字长”是指计算机 cpu 一次性处理的位数(目前通常为 32 位或 64 位)。数据总线大小、指令大小、地址大小通常是字大小的倍数。
例如,假设这个结构:

type data struct {
        a bool     // 1 byte
        b int64    // 8 byte
}

这个结构不是 9 bytes 因为,当我们的字大小为 8 时,对于第一个周期,cpu 读取 bool 的 1 byte 并为其他结构填充 7 bytes
想象一下:

p: padding
+-----------------------------------------+----------------+
| 1-byte bool | p | p | p | p | p | p | p |     int-64     |
+-----------------------------------------+----------------+
              first 8 bytes                 second 8 bytes

为了获得更好的性能,请将结构项从大到小排序。
这不是一个好的表现:

type data struct {
    a string // 16 bytes            size 16
    b int32  //  4 bytes            size 20
    //           4 bytes padding    size 24
    c string // 16 bytes            size 40
    d int32  //  4 bytes            size 44
    //           4 bytes padding    size 48 - aligned on 8 bytes
}

现在好多了:

type data struct {
    a string // 16 bytes            size 16
    c string // 16 bytes            size 32
    d int32  //  4 bytes            size 36
    b int32  //  4 bytes            size 40
    //           no padding         size 40 - Aligned on 5 bytes
}

请参阅 here 了解更多示例。

以上就是《是否可以在结构中使用填充项,如空格?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>