dsfgds4215 2016-08-21 11:10
浏览 182
已采纳

在Golang中优化数据结构/单词对齐填充

Similar to what I've learned in C++, I believe it's the padding that causes a difference in the size of instances of both structs.

type Foo struct {
    w byte //1 byte
    x byte //1 byte
    y uint64 //8 bytes
}
type Bar struct {
    x byte //1 byte
    y uint64 //8 bytes
    w byte// 1 byte
}
func main() {
    fmt.Println(runtime.GOARCH)
    newFoo := new(Foo)
    fmt.Println(unsafe.Sizeof(*newFoo))
    newBar := new(Bar)
    fmt.Println(unsafe.Sizeof(*newBar))
}

Output:

amd64
16
24
  • Is there a rule of thumb to follow when defining struct members? (like ascending/descending order of size of types)
  • Is there a compile time optimisation which we can pass, that can automatically take care of this?
  • Or shouldn't I be worried about this at all?
  • 写回答

2条回答 默认 最新

  • dongxinpa3101 2016-08-21 12:23
    关注

    Currently there's no compile-time optimisation; the values are padded to 8 bytes on x64.

    You can manually arrange structs to optimally utilise space; typically by going from larger types to smaller; 8 consecutive byte fields for example, will only use 8 bytes, but a single byte would be padded to an 8 byte alignment, consider this: https://play.golang.org/p/0qsgpuAHHp

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    type Compact struct {
        a, b                   uint64
        c, d, e, f, g, h, i, j byte
    }
    
    // Larger memory footprint than "Compact" - but less fields!
    type Inefficient struct {
        a uint64
        b byte
        c uint64
        d byte
    }
    
    func main() {
        newCompact := new(Compact)
        fmt.Println(unsafe.Sizeof(*newCompact))
        newInefficient := new(Inefficient)
        fmt.Println(unsafe.Sizeof(*newInefficient))
    }
    

    If you take this into consideration; you can optimise the memory footprint of your structs.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog