func memoryMapUint8() {
memoUint8 := map[string]uint8{}
for i := 0; i < 100; i++ {
memoUint8[strconv.Itoa(i)] = uint8(i)
}
}
func memoryMapBool() {
memoBool := map[string]bool{}
for i := 0; i < 100; i++ {
memoBool[strconv.Itoa(i)] = true
}
}
type Number struct {
Num uint8
}
func memoryMapStruct() {
memoStruct := map[string]Number{}
for i := 0; i < 100; i++ {
memoStruct[strconv.Itoa(i)] = Number{Num: uint8(i)}
}
fmt.Println(memoStruct)
}
测试:
import (
"testing"
)
func BenchmarkMemoryMapUint8(b *testing.B) {
for i := 0; i < b.N; i++ {
memoryMapUint8()
}
b.ReportAllocs()
}
func BenchmarkMemoryMapBool(b *testing.B) {
for i := 0; i < b.N; i++ {
memoryMapBool()
}
b.ReportAllocs()
}
func BenchmarkMemoryMapStruct(b *testing.B) {
for i := 0; i < b.N; i++ {
memoryMapStruct()
}
b.ReportAllocs()
}
结果:
allocs/op 表示每个操作(单次迭代)发生了多少个不同的内存分配。
B/op每个操作分配了多少字节.
TimeCunsume (ns/peroperation),MemBytes(),allocs越小代表性能越好。从数据来看结构体存储的内存占用稍微少一些,速度也更快。