Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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{}
like image 329
peerxu Avatar asked Mar 15 '16 00:03

peerxu


2 Answers

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
}
like image 131
Aruna Herath Avatar answered Nov 04 '22 14:11

Aruna Herath


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.

like image 29
Mike Reedell Avatar answered Nov 04 '22 14:11

Mike Reedell