首页

/

归档

/

友链

/

独立黑客

/

关于


Go语言性能优化实战

过早优化是万恶之源,这里都是黑魔法,不是性能瓶颈慎用

package main

type structDemoStruct struct {
    First int
}

var (
    mapDemo    = make(map[int]int, 1)
    structDemo = structDemoStruct{}
)

func mapIncr() {
    mapDemo[1]++
}

func structIncr() {
    structDemo.First++
}
package main

import (
    "testing"
)

func BenchmarkMap(b *testing.B) {
    for i := 0; i < b.N; i++ {
        mapIncr()
    }
}

func BenchmarkStruct(b *testing.B) {
    for i := 0; i < b.N; i++ {
        structIncr()
    }
}

测试结果:

$ go test -bench .
goos: linux
goarch: amd64
BenchmarkMap-4          100000000           20.5 ns/op
BenchmarkStruct-4       1000000000           2.02 ns/op
PASS
ok      _/home/jiajun/tests 4.299s