what's difference between make and initialize struct in golang?

huangapple go评论63阅读模式
英文:

what's difference between make and initialize struct in golang?

问题

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

ch := make(chan interface{})
o := struct{}{}

但是,使用make{}来创建映射有什么区别呢?

m0 := make(map[int]int)
m1 := map[int]int{}
英文:

We can make channel by make function, new an object by {} expression.

ch := make(chan interface{})
o := struct{}{}

But, what's difference between make and {} to new a map?

m0 := make(map[int]int)
m1 := map[int]int{}

答案1

得分: 13

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) // 输出 176 ns/op

    bwl := testing.Benchmark(BenchmarkWithLitteral)
    fmt.Println(bwl) // 输出 259 ns/op
}

希望这可以帮助到你!

英文:

make can be used to initialize a map with preallocated space. It takes an optional second parameter.

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

Allocation takes cpu time. If you know how many entries there will be in the map you can preallocate space to all of them. This reduces execution time. Here is a program you can run to verify this.

package main

import &quot;fmt&quot;
import &quot;testing&quot;

func BenchmarkWithMake(b *testing.B) {
	m0 := make(map[int]int, b.N)
	for i := 0; i &lt; b.N; i++ {
		m0[i] = 1000
	}
}

func BenchmarkWithLitteral(b *testing.B) {
	m1 := map[int]int{}
	for i := 0; i &lt; 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
}

答案2

得分: 1

make关键字的文档中可以看到:

> Map:根据指定的大小进行初始分配,但生成的映射长度为0。大小可以省略,此时会分配一个较小的初始大小。

因此,在使用映射时,使用make和使用空映射字面量没有区别。

英文:

From the docs for the make keyword:

> Map: An initial allocation is made according to the size but the
> resulting map has length 0. The size may be omitted, in which case a
> small starting size is allocated.

So, in the case of maps, there is no difference between using make and using an empty map literal.

huangapple
  • 本文由 发表于 2016年3月15日 08:57:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/36000871.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定