这样Go性能优化为什么无效

背景

在项目优化过程中,将循环中的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结果如下,可自行享用:在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值