我们和一位同事讨论了使用 map 作为列表的性能,并比较了 interface 作为 value( map[int]interface{}) 与空结构()的使用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{}{}
}
}
Run Code Online (Sandbox Code Playgroud)
测试
package main
import "testing"
func Benchmark_Interface(b *testing.B) {
for i := 0; i < b.N; i++ {
MapWithInterface()
}
}
func Benchmark_EmptyStruct(b …Run Code Online (Sandbox Code Playgroud)