Reduce the binary size of Go
Go has become 1 binary very well, but its 1 binary is quite big, but it may be a bit of a bottleneck.
The Go binary diet read an article that, the binary of Go tried to diet.
Ldflags = "- w"
The 1st shown -ldflags="-w" ** is a way to ensure that does not generate a symbol table of DWARF by.
% go build -ldflags="-w"
Ldflags = "- s"
Then, -ldflags="-s" is a way to ensure that does not generate all the symbol table to be used for debugging by.
% go build -ldflags="-s"
Up to this point it is common to, but had been then shown The Ultimate Packer for eXecutables was the way to use.
UPX
I did not know it widely, but UPX seems to be some software since 1998. Windows / Linux (i386 / ARM / MIPS) / Mac / * BSD and almost all major platforms will work. License GPL ( [注1] is). UPX compresses the binary while keeping the executable format.
The actual operation, 7-Zip for use in, say, LZMA leave compression on, Extract it at runtime and write it directly to memory before executing it. If it is impossible to replace it in memory, it will be written in a temporary file and executed.
The code required for decompression is only a few hundred bytes. Of course, CPU and memory are necessary for expansion, but it is only once, and I think that there is not much to be a problem if it is as big as Go binary.
result
I tried it on the code of a fairly large project at hand. OS used Mac OS, go 1.6 was used.
Object | Number of bytes |
---|---|
Former | 26 MB (27090756) |
"-w" | 19 MB (20414276) |
"-s" | 26 MB (27090756) |
"-w" + UPX (-9 o'clock) | 5.2 M (5443584) |
"-w" + UPX (-1 o'clock) | 6.4 M (6684672) |
Well, it has not changed in "-s" ... I think that it is something around ld that is not in the darwin environment, so it is something around it that I was chasing afterwards, the original 26 MB was reduced to 5.2 MB.
Compression to upx -9 when using, took time I will take a decent time at 15.70 seconds. It was about the same as running about 3 times. It was about 0.10 seconds when stretched. Of course it also depends on memory etc, so this result can not be taken as a swallowing but as a guide only.
More say, upx -1 If that is compressed by only takes 0.78 seconds. Yet, it was 6.4 MB and the compression efficiency was satisfactory. This area but I think that I be determined in accordance with the environment to target, -1 you also feel that enough.
Summary
The big problem of Go binary was that it could be solved to some extent by using ldflags and UPX. I did not know UPX, but it looks pretty amazing when I see the code.
[注1] | ライセンスについて。UPXはGPLに例外事項をつけたライセンスをとっ ています。これは、GPLであるUPXがバイナリにリンクする形となる ため、圧縮対象となるバイナリも通常はGPLになる必要があるのです が、リンクするUPXのコードを改変しないかぎりその必要はない、と いう例外条項です。 ライセンス を確認してい ただけると分かるように、商用プログラムに対して適用できると明 確に書かれています。 |