我们可以通过make
函数创建 channel ,通过{}
表达式新建一个对象。
ch := make(chan interface{})
o := struct{}{}
但是,make
和 {}
新建 map 有什么区别?
m0 := make(map[int]int)
m1 := map[int]int{}
最佳答案
make
可用于使用预分配空间初始化映射。它需要一个可选的第二个参数。
m0 := make(map[int]int, 1000)//为 1000 个条目分配空间
分配需要 cpu 时间。如果您知道映射中将有多少个条目,您可以为所有条目预分配空间。这减少了执行时间。您可以运行以下程序来验证这一点。
package main
import "fmt"
import "testing"
func BenchmarkWithMake(b *testing.B) {
m0 := make(map[int]int, b.N)
for i := 0; i < b.N; i++ {
m0[i] = 1000
}
}
func BenchmarkWithLitteral(b *testing.B) {
m1 := map[int]int{}
for i := 0; i < b.N; i++ {
m1[i] = 1000
}
}
func main() {
bwm := testing.Benchmark(BenchmarkWithMake)
fmt.Println(bwm) // gives 176 ns/op
bwl := testing.Benchmark(BenchmarkWithLitteral)
fmt.Println(bwl) // gives 259 ns/op
}
关于go - golang 中的 make 和 initialize struct 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000871/