简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM