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

标签 go

我们可以通过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/

相关文章:

postgresql - 与 postgreSQL 模式连接

go - 检查纬度/经度点是否在区域内

golang语法错误: unexpected in struct

javascript - 如何将 Google Go 与 Chrome 交互?

go - 如何修复 Go 中的 "zip: not a valid zip file"错误?

go - 如何从 PKCS#12 容器中提取私钥并将其保存为 PKCS#8 格式?

go - 从字符串 golang 中删除转义的双引号

go - 编码 utf 8 个字符的问题 - šđžčć

Golang 1.5 vendor - 找不到包

go - *[]Type 和 []*Type 在 go 中有什么区别