map[string]uint8 、map[string]bool 、map[string]struct{} 各自存100条数据,实际占用的存储空间对比

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越小代表性能越好。从数据来看结构体存储的内存占用稍微少一些,速度也更快。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值