背景
在项目优化过程中,将循环中的a.b.c取值操作,提取到循环外赋值,在循环中直接复用结果,本想可以优化性能,但是最后结果啪啪打脸,性能丝毫不为所动。
这不科学!!!本着打破砂锅问到底的精神,来一问到底。
代码
talk is cheap, show you the code, benchmark test code
package main
import (
"testing"
)
type TA struct {
a int
}
type TB struct {
a TA
}
type TC struct {
b TB
}
type TD struct {
c TC
}
type TE struct {
d TD
}
func getAdd(n int, m int) int {
return n * n * n + m
}
func Benchmark_direct(b *testing.B) {
s := 0
e := TE{d: TD{ c: TC{ b: TB{a: TA{a:2}}}}}
for n := 0; n < b.N; n++ {
s = getAdd(e.d.c.b.a.a, s)
}
b.Log("Benchmark_direct", s)
}
func Benchmark_cache(b *testing.B) {
s := 0
e := TE{d: TD{ c: TC{ b: TB{a: TA{a:2}}}}}
tmp := e.d.c.b.a.a
for n := 0; n < b.N; n++ {
s = getAdd(tmp, s)
}
b.Log("Benchmark_cache", s)
}
func Benchmark_noop(b *testing.B) {
for n := 0; n < b.N; n++ {
}
}
测试
代码中,构建三个场景:空循环、循环内取值、循环外取值,测试结果如下
MacBook-Pro-2:go_test hl$ go test -bench=. duration_test.go
goos: darwin
goarch: amd64
Benchmark_direct-4 1000000000 0.579 ns/op
— BENCH: Benchmark_direct-4
duration_test.go:33: Benchmark_direct 8
duration_test.go:33: Benchmark_direct 800
duration_test.go:33: Benchmark_direct 80000
duration_test.go:33: Benchmark_direct 8000000
duration_test.go:33: Benchmark_direct 800000000
duration_test.go:33: Benchmark_direct 8000000000
Benchmark_cache-4 1000000000 0.574 ns/op
— BENCH: Benchmark_cache-4
duration_test.go:43: Benchmark_cache 8
duration_test.go:43: Benchmark_cache 800
duration_test.go:43: Benchmark_cache 80000
duration_test.go:43: Benchmark_cache 8000000
duration_test.go:43: Benchmark_cache 800000000
duration_test.go:43: Benchmark_cache 8000000000
Benchmark_noop-4 1000000000 0.574 ns/op
PASS
ok command-line-arguments 2.003s
运行结果:三个函数运行时间结果几乎没有差别
真相是什么
为什么会这样呢,难道e.d.c.b.a.a这个操作有缓存
重剑无锋,大巧不工,看看Golang编译后的汇编代码找答案吧
go tool compile -S duration_test.go > duration_test_src.txt
查看Benchmark_direct、Benchmark_cache汇编源码,发现其代码是一致的,可以证明其确实有缓存,并不用每次都去做e.d.c.b.a.a操作
diff结果如下,可自行享用: