很多童鞋都忽略了这个问题,认为map[]bool 和 map[]struct{} 它们两个之间没有差异,其实并非如此。
我们通过golang自带的benchmark 压测功能,创建三种类型的map,然后往里面添加2²⁴ -1 个数据。
package main
import (
"testing"
)
const it = uint(1 << 24)
// 测试map[uint]bool
func BenchmarkSetWithBoolValueWrite(b *testing.B) {
set := make(map[uint]bool)
for i := uint(0); i < it; i++ {
set[i] = true
}
}
// 测试map[uint]struct{}
func BenchmarkSetWithStructValueWrite(b *testing.B) {
set := make(map[uint]struct{})
for i := uint(0); i < it; i++ {
set[i] = struct{}{}
}
}
// 测试map[uint]interface{}
func BenchmarkSetWithInterfaceValueWrite(b *testing.B) {
set := make(map[uint]interface{})
for i := uint(0); i < it; i++ {
set[i] = struct{}{}
}
}
运行一下
# GOMAXPROCS=1 go test -v -bench=. -count=3 -run=none -benchmem | tee bench.txt
# benchstat bench.txt
具体结果如下:
name time/op
SetWithBoolValueWrite 3.27s ± 0%
SetWithStructValueWrite 3.12s ± 0%
SetWithInterfaceValueWrite 5.96s ± 0%
name alloc/op
SetWithBoolValueWrite 884MB ± 0%
SetWithStructValueWrite 802MB ± 0%
SetWithInterfaceValueWrite 1.98GB ± 0%
结论:
可以看到使用 struct{} 比使用 bool 类型速度要快,并且内存开销也更小。总之尽量少用interface{} 它是速度最慢,内存开销最大的一种方式。这是因为interface{} 在底层单独使用了一种类型保存。
页面更新:2024-03-13
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号