为什么导入NATS Golang客户端会使可执行文件大小增加5MB?

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

Why the NATS Golang client, if imported increases the executable size by 5MB?

问题

我正在评估NATS以用于我即将开始的项目。在测试过程中,我注意到当我添加NATS客户端的导入行并从库中使用几个简单的调用时,编译后的可执行文件的大小从大约2MB增加到7MB。

我正在使用Linux Mint 20.3,Golang 1.18,NATS库的版本是:github.com/nats-io/nats.go v1.16.0。

有人能解释一下为什么一个只用于与服务器进行接口交互的库会给二进制文件添加如此庞大的代码量吗?

有没有办法减小这个文件大小?

英文:

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?

答案1

得分: 1

这种情况并不罕见。你导入的代码不仅包括接口,还包括所有的接口实现和依赖项。

Golang在使用时不会对导入的代码进行树摇优化(如果能够进行优化就好了),这导致所有未使用的代码也会被导入和编译。

其他一些例子中,你可能会看到这种增加的情况,比如导入kubernetes go模块会增加约12MB的大小,或者使用librdkafka kafka会增加几MB的大小。

你可以通过使用编译器标志来减少增长:

go build -ldflags "-s -w"

这会去除一些调试信息,从而稍微减小大小。

你看到的大小减小(如果有的话),不仅仅是由于NATS导入造成的。它也可能来自其他导入(所以如果你想看到这些标志的真实影响,请进行基准测试)。

英文:

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)

huangapple
  • 本文由 发表于 2022年7月24日 22:37:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/73099361.html
匿名

发表评论

匿名网友

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

确定