你好,哈布罗夫派。在“ Golang开发人员”课程开始前夕,我们已经为您准备了一份有趣的翻译。
如果您急切需要将Go二进制文件的大小减少6%,那么本文适合您。(我在Tailscale的帮助下进行了此实验。请注意,我是投资者。)如果您不太在意二进制大小,那么,您可能至少有兴趣阅读本文。
为了获得本文的一些粗略数字,我获取了GOPATH中遇到的第一个文件。本文中的所有特定数字均指github.com/mvdan/sh/cmd/shfmt
。经过一些实验,它们对我来说似乎很具有代表性。
我使用Go工具链提交9d812cfa5c作为基本提交。这是截至2020年4月29日的主分支;它可能类似于Go版本1.15beta1。我使用的是Go 1.14,而不是Go,因为它包括减少二进制文件大小的方法,其中包括一种特定的方法,如果大小对您很重要的话,您肯定会需要。
. , , . sync.Once. . (… , ). , : -ldflags=-w go build.
, . . , .
Go , . , Go. . . . ( .)
.
. .
. . , ( gofmt) , .
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, playground")
}
package main
import ( "fmt" ); func main() { fmt.Println("Hello, playground") }
Go , .
--- a/src/cmd/compile/internal/syntax/pos.go
+++ b/src/cmd/compile/internal/syntax/pos.go
@@ -23,3 +23,3 @@ type Pos struct {
// MakePos Pos PosBase, .
-func MakePos(base *PosBase, line, col uint) Pos { return Pos{base, sat32(line), sat32(col)} }
+func MakePos(base *PosBase, line, col uint) Pos { return Pos{base, 1, 1} }
@@ -101,2 +101,3 @@ type PosBase struct {
func NewFileBase(filename string) *PosBase {
+ filename = "x.go"
base := &PosBase{MakePos(nil, linebase, colbase), filename, linebase, colbase}
x.go
, 1. ( , DWARF).
. , , x.go:1:1
.
DWARF . : DWARF, DWARF .
- cgo. , cgo. (, ), .
https://github.com/josharian/go/commit/1a3e66ceed.
, , x.go:1:1
.
, -ldflags=-w
, 3,126,800 2,938,384 , 6%.
. - .
-:
func f(x []byte) {
_ = x[0]
_ = x[1]
}
func f(x []byte) {
_, _ = x[0], x[1]
}
go tool compile -S x.go
, , runtime.panicIndex
. . , runtime.panicIndex
, , . , . - , .
, , .
, ? , . - , , . . x.go:1
. , , . Pprof - , , , .
. , ? 0,9%. , , 1 5,1%.
, . , , 16? diff :
--- a/src/cmd/compile/internal/syntax/pos.go
+++ b/src/cmd/compile/internal/syntax/pos.go
@@ -23,3 +23,3 @@ type Pos struct {
// MakePos Pos PosBase, .
-func MakePos(base *PosBase, line, col uint) Pos { return Pos{base, 1, 1} }
+func MakePos(base PosBase, line, col uint) Pos { return Pos{base, sat32(line/1616 + 1), 1} }
2,2%. . , 16? , , , «» .
--- a/src/cmd/compile/internal/syntax/pos.go
+++ b/src/cmd/compile/internal/syntax/pos.go
@@ -23,3 +23,3 @@ type Pos struct {
// MakePos Pos PosBase, .
-func MakePos(base *PosBase, line, col uint) Pos { return Pos{base, 1, 1} }
+func MakePos(base *PosBase, line, col uint) Pos { return Pos{base, sat32(line/16 + 1), 1} }
2,75%! /16
0,5% , /16*16
?
varint . , .