io: optimize WriteString, avoid allocation

name                          old time/op    new time/op    delta
AppExecResult_EncodeBinary-8     477ns ± 0%     467ns ± 3%     ~     (p=0.190 n=4+5)

name                          old alloc/op   new alloc/op   delta
AppExecResult_EncodeBinary-8      376B ± 0%      368B ± 0%   -2.13%  (p=0.008 n=5+5)

name                          old allocs/op  new allocs/op  delta
AppExecResult_EncodeBinary-8      5.00 ± 0%      4.00 ± 0%  -20.00%  (p=0.008 n=5+5)
This commit is contained in:
Roman Khimov 2021-11-30 19:07:10 +03:00
parent 748a70569a
commit e236ac4067

View file

@ -143,7 +143,11 @@ func (w *BinWriter) WriteVarBytes(b []byte) {
// WriteString writes a variable length string into the underlying io.Writer.
func (w *BinWriter) WriteString(s string) {
w.WriteVarBytes([]byte(s))
w.WriteVarUint(uint64(len(s)))
if w.Err != nil {
return
}
_, w.Err = io.WriteString(w.w, s)
}
// Grow tries to increase underlying buffer capacity so that at least n bytes