1 回答

TA貢獻1829條經驗 獲得超9個贊
[]字節到字符串
對于[]bytetostring轉換,編譯器在可以證明時生成對內部runtime.slicebytetostringtmp函數的調用(鏈接到源)
在調用 goroutine 可能修改原始切片或與另一個 goroutine 同步之前,字符串形式將被丟棄。
runtime.slicebytetostringtmp返回string對實際[]byte字節的引用,因此它不會分配。函數中的注釋說
// First such case is a m[string(k)] lookup where
// m is a string-keyed map and k is a []byte.
// Second such case is "<"+string(b)+">" concatenation where b is []byte.
// Third such case is string(b)=="foo" comparison where b is []byte.
簡而言之,對于一個b []byte
:
地圖查找
m[string(b)]
不分配"<"+string(b)+">
串聯不分配string(b)=="foo"
比較不分配
第二次優化于2015年1月22日實施,在go1.6
第三次優化于2015年1月27日實施,在go1.6
因此,例如,在以下內容中:
var bs []byte = []byte{104, 97, 108, 108, 111}
func main() {
x := string(bs) == "hello"
println(x)
}
比較不會導致 go1.6 中的分配。
字符串到 []byte
同樣,runtime.stringtoslicebytetmp函數(鏈接到源)說:
// Return a slice referring to the actual string bytes.
// This is only for use by internal compiler optimizations
// that know that the slice won't be mutated.
// The only such case today is:
// for i, c := range []byte(str)
所以i, c := range []byte(str)不分配,但你已經知道了。
- 1 回答
- 0 關注
- 207 瀏覽
添加回答
舉報