Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will go compilers ignore unused functions

Tags:

go

executable

If there is a function from an external package that is not used at all in my project, will the compiler remove the function from the generated machine code?

This question could be targeted at any language compiler in general. But, I think the behaviour may vary language to language. So, I am interested in knowing what does go compilers do.

I would appreciate any help on understanding this.

like image 320
Sidtharthan Avatar asked Feb 08 '18 15:02

Sidtharthan


1 Answers

The language spec does not mention this anywhere, and from a correctness point of view this is irrelevant.

But know that the current version does remove certain constructs that the compiler can prove is not used and will not change the runtime behaviour of the app.

Quoting from The Go Blog: Smaller Go 1.7 binaries:

The second change is method pruning. Until 1.6, all methods on all used types were kept, even if some of the methods were never called. This is because they might be called through an interface, or called dynamically using the reflect package. Now the compiler discards any unexported methods that do not match an interface. Similarly the linker can discard other exported methods, those that are only accessible through reflection, if the corresponding reflection features are not used anywhere in the program. That change shrinks binaries by 5–20%.

Methods are a "harder" case than functions because methods can be listed and called with reflection (unlike functions), but the Go tools do what they can even to remove unused methods too.

You can see examples and proof of removed / unlinked code in this answer:

How to remove unused code at compile time?

Also see other relevant questions:

Splitting client/server code

Call all functions with special prefix or suffix in Golang

like image 197
icza Avatar answered Sep 20 '22 00:09

icza