Go语言性能优化实战

栏目: Go · 发布时间: 5年前

内容简介:测试结果:

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

  • 根据pprof数据优化
  • 尽量避免GC,所以要避免创建过多的对象,也可以通过设置 GOGC 环境变量来增加触发GC的阈值,缺点是费内存。
  • 尽量的复用已经创建的对象,其中就包括如果可以的话,预先创建好对象。参考: https://golang.org/pkg/sync/#Pool
  • 避免锁,可以考虑 CAS。 https://golang.org/pkg/sync/atomic/
  • 如果可以的话,用struct代替map。一个简单的例子就可以说明:
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
defer
time.Now
[]byte
GOGC

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Lean Startup

The Lean Startup

Eric Ries / Crown Business / 2011-9-13 / USD 26.00

更多中文介绍:http://huing.com Most startups fail. But many of those failures are preventable. The Lean Startup is a new approach being adopted across the globe, chan ging the way companies are built and ......一起来看看 《The Lean Startup》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具