我们和一位同事讨论了使用映射作为列表的性能,并比较了使用接口作为 value( map[int]interface{}) 与空 struct() 的性能map[int]struct{}),我们在基准测试中得到了一些奇怪的值。
代码
package main
func main() {}
func MapWithInterface() {
m := map[int]interface{}{}
for i := 1; i <= 100; i++ {
m[i] = nil
}
}
func MapWithEmptyStruct() {
m := map[int]struct{}{}
for i := 1; i <= 100; i++ {
m[i] = struct{}{}
}
}
测试
package main
import "testing"
func Benchmark_Interface(b *testing.B) {
for i := 0; i < b.N; i++ {
MapWithInterface()
}
}
func Benchmark_EmptyStruct(b *testing.B) {
for i := 0; i < b.N; i++ {
MapWithEmptyStruct()
}
}
结果
go version go1.15.5 darwin/amd64
go test -bench=. -benchmem
goos: darwin
goarch: amd64
pkg: awesomeProject1
Benchmark_Interface-8 130419 8949 ns/op 7824 B/op 7 allocs/op
Benchmark_EmptyStruct-8 165147 6964 ns/op 3070 B/op 17 allocs/op
PASS
ok awesomeProject1 3.122s
问题
因此,空结构版本似乎运行得更快,使用的内存更少,但分配更多,无法弄清楚原因。有谁知道为什么会这样?
慕慕森
相关分类