gf框架之并发安全容器 - gmap,以及与sync.Map的性能比较

lyelyelye 2019-06-26

相关链接:http://gf.johng.cn/494392

gf框架提供了几个非常实用的并发安全容器,其中gmap就是项目开发中最常用的一个。

gmap具体的方法请参考godoc:https://godoc.org/github.com/...

gmap内部有多个类型结构体定义,包括:IntBoolMap、IntIntMap、IntInterfaceMap、IntStringMap、InterfaceInterfaceMap、StringBoolMap、StringIntMap、StringInterfaceMap、StringStringMap、UintInterfaceMap。

从执行效率上考虑,基于不同的需求场景,选择合适的类型结构体,其执行效率是不一样的,以下使用基准测试来对比各个类型的写入性能(测试代码):

john@johnstation:~/Workspace/Go/GOPATH/src/gitee.com/johng/gf/g/container/gmap$ go test gmap_test.go -bench=".*"
goos: linux
goarch: amd64
BenchmarkIntBoolMap_Set-8                  10000000           171 ns/op
BenchmarkIntIntMap_Set-8                   10000000           181 ns/op
BenchmarkIntInterfaceMap_Set-8             10000000           227 ns/op
BenchmarkIntStringMap_Set-8                10000000           271 ns/op
BenchmarkInterfaceInterfaceMap_Set-8        5000000           331 ns/op
BenchmarkStringBoolMap_Set-8                5000000           271 ns/op
BenchmarkStringIntMap_Set-8                 5000000           300 ns/op
BenchmarkStringInterfaceMap_Set-8           5000000           363 ns/op
BenchmarkStringStringMap_Set-8              5000000           394 ns/op
BenchmarkUintInterfaceMap_Set-8            10000000           275 ns/op
PASS
ok      command-line-arguments    37.024s

此外,需要说明的是,go语言从1.9版本开始引入了同样支持并发安全的sync.Map,我们来看看基准测试结果怎么样:

john@johnstation:~/Workspace/Go/GOPATH/src/gitee.com/johng/gf/g/container/gmap$ go test *.go -bench=".*"
goos: linux
goarch: amd64
BenchmarkGmapSet-8            10000000           181 ns/op
BenchmarkSyncmapSet-8          5000000           366 ns/op
BenchmarkGmapGet-8            30000000            82.6 ns/op
BenchmarkSyncmapGet-8         20000000            95.7 ns/op
BenchmarkGmapRemove-8         20000000            69.8 ns/op
BenchmarkSyncmapRmove-8       20000000            93.6 ns/op
PASS
ok      command-line-arguments    27.950s

查看sync.Map的源代码我们可以发现,其实现原理类似于gmap.InterfaceInterfaceMap这个类型结构体,但是效率却没有gmap.InterfaceInterfaceMap高。

因此可以发现,支持并发安全的gmap包的效率已经相当地高。