英文:
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 "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
}
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论