golang 中的 make 和 initialize struct 有什么区别?

我们可以通过make函数创建通道,通过{}表达式创建新对象。


ch := make(chan interface{})

o := struct{}{}

但是,新地图make和{}新地图有什么区别?


m0 := make(map[int]int)

m1 := map[int]int{}


陪伴而非守候
浏览 206回答 2
2回答

波斯汪

make可用于初始化具有预分配空间的映射。它需要一个可选的第二个参数。m0 := make(map[int]int, 1000) // allocateds space for 1000 entries分配需要 CPU 时间。如果您知道地图中将有多少条目,您可以为所有条目预先分配空间。这减少了执行时间。这是您可以运行的程序来验证这一点。package mainimport "fmt"import "testing"func BenchmarkWithMake(b *testing.B) {&nbsp; &nbsp; m0 := make(map[int]int, b.N)&nbsp; &nbsp; for i := 0; i < b.N; i++ {&nbsp; &nbsp; &nbsp; &nbsp; m0[i] = 1000&nbsp; &nbsp; }}func BenchmarkWithLitteral(b *testing.B) {&nbsp; &nbsp; m1 := map[int]int{}&nbsp; &nbsp; for i := 0; i < b.N; i++ {&nbsp; &nbsp; &nbsp; &nbsp; m1[i] = 1000&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; bwm := testing.Benchmark(BenchmarkWithMake)&nbsp; &nbsp; fmt.Println(bwm) // gives 176 ns/op&nbsp; &nbsp; bwl := testing.Benchmark(BenchmarkWithLitteral)&nbsp; &nbsp; fmt.Println(bwl) // gives 259 ns/op}

倚天杖

来自make关键字的文档:映射:根据大小进行初始分配,但结果映射的长度为 0。大小可以省略,在这种情况下,分配的起始大小较小。因此,就地图而言,使用make和使用空地图文字没有区别。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go