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

pee*_*rxu 3 go

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

ch := make(chan interface{})
o := struct{}{}
Run Code Online (Sandbox Code Playgroud)

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

m0 := make(map[int]int)
m1 := map[int]int{}
Run Code Online (Sandbox Code Playgroud)

Aru*_*ath 8

make可用于初始化具有预分配空间的地图.它需要一个可选的第二个参数.

m0 := make(map[int]int, 1000) // allocateds space for 1000 entries

分配需要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
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*ell 1

从关键字的文档中make

Map:根据大小进行初始分配,但结果映射的长度为 0。可以省略大小,在这种情况下分配较小的起始大小。

make因此,就地图而言,使用和使用空地图文字没有区别。