Home > front end >  Why the NATS Golang client, if imported increases the executable size by 5MB?
Why the NATS Golang client, if imported increases the executable size by 5MB?

Time:07-25

I'm evaluating the NATS for my upcoming project. Why testing it I noticed that the size of the compiled executable goes from around 2MB to 7MB when I add the import line for the NATS client and use a few simple calls from the library.

I'm using Linux Mint 20.3, with Golang 1.18, the NATS library is: github.com/nats-io/nats.go v1.16.0

Can anyone explain why a library that's only supposed to interface with the server, adds such an enormous amount of code to the binary?

Is there any way to reduce this?

CodePudding user response:

It is not uncommon that this happens. The code you import is not just the interface, but also all the interface implementation, and dependencies. Golang does not treeshake the imports on usage (would be nice if it does), resulting in also all the unused code to be imported and compiled.

Other examples where you will see this kind of increases is for example importing the kubernetes go mods which adds ~12MB, or usage of librdkafka kafka (several MB)

You might be able to reduce the growth with the use of compiler flags:

go build -ldflags "-s -w"

which takes out some debug information and which can reduce the size again a bit.

The size reduction you see (if any), is not just from the NATS import. It might also be from other imports (so benchmark if you want to see the real impact of these flags)

  • Related