You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用binary.Write编码结构体切片时,短切片内存占用超出预期的问题咨询

使用binary.Write编码结构体切片时,短切片内存占用超出预期的问题咨询

大家好,我最近在用Go标准库encoding/binary里的binary.Write编码结构体切片时,碰到了个挺奇怪的情况——处理短切片的路径下,内存分配量比我预想的要高不少。为了复现这个问题,我在encoding/binary包下写了两个基准测试用例,代码如下:

import (
    "bytes"
    "io"
    "testing"
    "encoding/binary"
)

type Struct struct {
    Int8       int8
    Int16      int16
    Int32      int32
    Int64      int64
    Uint8      uint8
    Uint16     uint16
    Uint32     uint32
    Uint64     uint64
    Float32    float32
    Float64    float64
    Complex64  complex64
    Complex128 complex128
    Array      [4]uint8
    Bool       bool
    BoolArray  [4]bool
}

// 计算切片总大小的辅助函数
func Size(slice []Struct) int {
    return binary.Size(slice[0]) * len(slice)
}

func BenchmarkWriteSlice1000Structs(b *testing.B) {
    slice := make([]Struct, 1000)
    buf := new(bytes.Buffer)
    var w io.Writer = buf
    b.SetBytes(int64(Size(slice)))
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        buf.Reset()
        binary.Write(w, binary.BigEndian, slice)
    }
    b.StopTimer()
}

func BenchmarkWriteSlice10Structs(b *testing.B) {
    slice := make([]Struct, 10)
    buf := new(bytes.Buffer)
    var w io.Writer = buf
    b.SetBytes(int64(Size(slice)))
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        buf.Reset()
        binary.Write(w, binary.BigEndian, slice)
    }
    b.StopTimer()
}

我发现处理包含10个Struct的切片时,内存分配的表现和处理1000个的情况差异明显,完全超出了我的预期。想请教下社区里的各位,有没有遇到过类似的问题?或者能帮忙分析下这背后可能的原因是什么?

备注:内容来源于stack exchange,提问作者Kwaku Biney

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 11:24:51