The Go Programming Language Specification
Defer statements
A 「推遲」 語句調用它的執行被推遲到 此刻周圍的函數返回的功能,要麼是因爲 周圍函數執行return語句,其功能體達到了 的末尾,或者是因爲相應的門廳是 恐慌。
go/src/runtime/stack.go
:
func adjustdefers(gp *g, adjinfo *adjustinfo) {
// Adjust defer argument blocks the same way we adjust active stack frames.
tracebackdefers(gp, adjustframe, noescape(unsafe.Pointer(adjinfo)))
// Adjust pointers in the Defer structs.
// Defer structs themselves are never on the stack.
for d := gp._defer; d != nil; d = d.link {
adjustpointer(adjinfo, unsafe.Pointer(&d.fn))
adjustpointer(adjinfo, unsafe.Pointer(&d.sp))
adjustpointer(adjinfo, unsafe.Pointer(&d._panic))
}
}
go/src/runtime/stack.go
:
// Copies gp's stack to a new stack of a different size.
// Caller must have changed gp status to Gcopystack.
//
// If sync is true, this is a self-triggered stack growth and, in
// particular, no other G may be writing to gp's stack (e.g., via a
// channel operation). If sync is false, copystack protects against
// concurrent channel operations.
func copystack(gp *g, newsize uintptr, sync bool) {
// . . .
// allocate new stack
new := stackalloc(uint32(newsize))
if stackPoisonCopy != 0 {
fillstack(new, 0xfd)
}
// . . .
// Compute adjustment.
var adjinfo adjustinfo
adjinfo.old = old
adjinfo.delta = new.hi - old.hi
// . . .
// Adjust remaining structures that have pointers into stacks.
// We have to do most of these before we traceback the new
// stack because gentraceback uses them.
adjustctxt(gp, &adjinfo)
adjustdefers(gp, &adjinfo)
adjustpanics(gp, &adjinfo)
if adjinfo.sghi != 0 {
adjinfo.sghi += adjinfo.delta
}
// . . .
}
從我的代碼的讀取,當一個夠程小號調整大小adjustdefers
對延遲函數進行指針調整。
你說你正在運行一個Go程序,它大部分時間都在做GC。第二高的包是github.com/pelletier/go-buffruneio
。代碼看起來效率低下。這是閱讀符文的簡單基準。
package main
import (
"bufio"
"bytes"
"io"
"testing"
"github.com/pelletier/go-buffruneio"
)
var buf = make([]byte, 64*1024)
func BenchmarkBuffruneio(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
r := buffruneio.NewReader(bytes.NewBuffer(buf[:cap(buf)]))
for {
rune, _, err := r.ReadRune()
if err == io.EOF || rune == buffruneio.EOF {
break
}
}
}
}
func BenchmarkBufio(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
r := bufio.NewReader(bytes.NewBuffer(buf[:cap(buf)]))
for {
_, _, err := r.ReadRune()
if err == io.EOF {
break
}
}
}
}
輸出:
$ go test -v -bench=.
goos: linux
goarch: amd64
pkg: so/runes
BenchmarkBuffruneio-2 200 9395482 ns/op 4198721 B/op 131078 allocs/op
BenchmarkBufio-2 3000 333731 ns/op 4208 B/op 2 allocs/op
PASS
ok so/runes 3.878s
$