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?
2条回答 默认 最新
duanlei0282 2014-10-20 22:44关注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
Testfromfunc 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.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报