2 回答

TA貢獻1921條經驗 獲得超9個贊
就像一些進一步的信息。一些基準代碼和內存分析顯示,從 go 1.5.3 開始,兩種方法都從堆中分配相同數量的內存,即以任何一種方式進行新副本。在從字節切片構建字符串時,編譯器調用一個例程來制作字節的唯一副本——因為字符串是不可變的,而字節切片則不是。
$ go tool pprof -alloc_space so002.test cprof0
Entering interactive mode (type "help" for commands)
(pprof) list copy
Total: 9.66MB
9.62MB 9.62MB (flat, cum) 99.55% of Total
. . 15:
. . 16:var global string
. . 17:
. . 18:func benchmarkcopy(b *testing.B, c int) {
. . 19: big := "This is a long string"
. 240B 20: parts := strings.Split(big, " ")
. . 21: old := parts[0]
. . 22: jlimit := 100
. . 23: for i := 0; i < b.N; i++ {
. . 24: for j := 0; j < jlimit; j++ {
3.21MB 3.21MB 25: global = string([]byte(old))
. . 26: }
. . 27: for j := 0; j < jlimit; j++ {
. . 28: b := []byte(old)
3.21MB 3.21MB 29: global = string(b)
. . 30: }
. . 31: for j := 0; j < jlimit; j++ {
3.21MB 3.21MB 32: new := make([]byte, len(old))
. . 33: copy(new, old)
. . 34: global = string(old)
. . 35: }
. . 36: }
. . 37:}

TA貢獻2041條經驗 獲得超4個贊
為確保 Go 不會將底層字符串保留在內存中,您必須將其顯式復制到新位置:
func unslice(old string) string {
new := make([]byte,len(old))
copy(new,old)
return string(old)
}
SmallString := unslice(BigString[0:7])
- 2 回答
- 0 關注
- 831 瀏覽
添加回答
舉報