内容简介:测试结果:
过早优化是万恶之源,这里都是黑魔法,不是性能瓶颈慎用
- 根据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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Java Servlet & JSP Cookbook
Bruce W. Perry / O'Reilly Media / 2003-12-1 / USD 49.99
With literally hundreds of examples and thousands of lines of code, the Java Servlet and JSP Cookbook yields tips and techniques that any Java web developer who uses JavaServer Pages or servlets will ......一起来看看 《Java Servlet & JSP Cookbook》 这本书的介绍吧!