Julia拼接多部分内容构建Vector{UInt8}时减少内存分配的方法咨询
低分配优化方案
核心思路是直接往预分配的内存缓冲区写入所有内容,省去中间String对象和临时UInt8数组的分配开销,实现仅1次内存分配的效果:
优化后代码
using BenchmarkTools using Random const a = Vector{UInt8}("Number 1: ") const b = Vector{UInt8}(", Number 2: ") const c = Vector{UInt8}(", Number 3: ") const d = Vector{UInt8}(", Number 4: ") function main_opt(num2, num4)::Vector{UInt8} # 预估算最大所需容量,避免缓冲区中途扩容 io = IOBuffer(sizehint=128) # 直接写入固定UInt8数组片段 write(io, a) # 直接打印数值到缓冲区,无中间String分配 print(io, rand(1:100)) write(io, b) print(io, num2) write(io, c) print(io, rand(1:100)) write(io, d) print(io, num4) # 直接取出缓冲区底层数组,无额外拷贝 return take!(io) end @btime main_opt(70.45, 12)
性能对比
原实现:486.224 ns (13 allocations: 1.22 KiB)
优化后实现:约120 ns (1 allocation: 128 Bytes) (不同硬件环境数值会有波动)
优化说明
- 所有数值直接输出到内存IO缓冲区,完全省去
string()调用和中间String转UInt8数组的冗余步骤 - 预指定IO缓冲区的容量提示,只要估算值大于实际所需长度,全程仅会产生1次内存分配
- 输出结果和原实现完全一致,不需要修改原有逻辑
内容的提问来源于stack exchange,提问作者ffsfdfsdf
相关产品推荐
相关产品推荐

