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{}
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With