Go语言 map里面塞 bool 和 空struct 性能差异

很多童鞋都忽略了这个问题,认为map[]bool 和 map[]struct{} 它们两个之间没有差异,其实并非如此。

Go语言 map里面塞 bool 和 空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

标签:差异   并非如此   开销   底层   结论   内存   性能   速度   两个   语言   类型   功能   方式   测试   数据   科技

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top