Go编译器的技巧

huangapple go评论80阅读模式
英文:

Go compiler tricks

问题

我在一次讲座中读到,Go编译器会主动删除输出二进制文件中未使用的代码。这个讲座中提到了一些在测试中有用的代码添加方法,但我找不到这个讲座的具体信息。是否有人对这个工作原理有更多了解?是否有关于高级测试技术的讲座?

英文:

I read in a talk that the Go compiler will aggressively remove code that isn't used in the output binary. The talk which I can't find used this for adding some code useful to testing. Does anybody have more information on how this works? Are there talks on advanced testing techniques?

答案1

得分: 0

Dave Cheney在他的基准测试博客文章中谈到了这个问题:

http://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go(关于编译器优化的说明)

英文:

Dave Cheney talks about this in his benchmark blog article:

http://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go (A note on compiler optimisations)

答案2

得分: 0

【Go语言的五个加速要素】

【Dave Cheney】

死代码消除

func Test() bool { return false }

func Expensive() {
    if Test() {
        // something expensive
    }
}

在这个例子中,尽管函数Test总是返回false,但Expensive函数在不执行Test的情况下无法知道这一点。

当Test函数被内联时,我们得到以下代码:

func Expensive() {
    if false {
        // something expensive is
        // now unreachable
    }
}

编译器现在知道这段昂贵的代码是不可达的。

这不仅节省了调用Test的成本,还节省了编译或运行任何现在不可达的昂贵代码的成本。


例如,添加一些对测试有用的代码:

func Complicated() {
    if Test() {
        // something for testing
    }
}

Test

func Test() bool { return false }

内联后

func Complicated() {
    if false {
        // something for testing
        // unreachable
    }
}

变为

func Test() bool { return true }

内联后

func Complicated() {
    if true {
        // something for testing
        // reachable
    }
}

可以用于包含仅用于测试的代码。

【1】:Go语言的五个加速要素
【2】:Dave Cheney

英文:

> Five things that make Go fast
>
> Dave Cheney
>
> Dead Code Elimination
>
> func Test() bool { return false }
>
> func Expensive() {
> if Test() {
> // something expensive
> }
> }
>
> In this example, although the function Test always returns false,
> Expensive cannot know that without executing it.
>
> When Test is inlined, we get something like this
>
> func Expensive() {
> if false {
> // something expensive is
> // now unreachable
> }
> }
>
> The compiler now knows that the expensive code is unreachable.
>
> Not only does this save the cost of calling Test, it saves compiling
> or running any of the expensive code that is now unreachable.


For example, adding some code useful to testing,

func Complicated() {
	if Test() {
		// something for testing
	}
}

Switching Test from

func Test() bool { return false }

inlined

func Complicated() {
	if false {
		// something for testing
		// unreachable
	}
}

to

func Test() bool { return true }

inlined

func Complicated() {
	if true {
		// something for testing
		// reachable
	}
}

can be useful to include code just for testing.

huangapple
  • 本文由 发表于 2014年10月20日 23:24:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/26469244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定