From 7e6f7ce4cfb577a14999a2434db94c8bb3befa82 Mon Sep 17 00:00:00 2001 From: Adam Scarr Date: Tue, 8 Aug 2017 19:54:34 +1000 Subject: [PATCH] Reduce string allocations for plain strings --- parser.go | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/parser.go b/parser.go index 741df56..f92266e 100644 --- a/parser.go +++ b/parser.go @@ -219,7 +219,7 @@ func String(allowedQuotes string) Parser { var end int = ps.Pos + 1 inputLen := len(ps.Input) - result := &bytes.Buffer{} + var buf *bytes.Buffer for end < inputLen { switch ps.Input[end] { @@ -229,6 +229,10 @@ func String(allowedQuotes string) Parser { return Node{} } + if buf == nil { + buf = bytes.NewBufferString(ps.Input[ps.Pos+1 : end]) + } + c := ps.Input[end+1] if c == 'u' { if end+6 >= inputLen { @@ -243,19 +247,26 @@ func String(allowedQuotes string) Parser { ps.Error.pos = end + 2 return Node{} } - result.WriteRune(r) + buf.WriteRune(r) end += 6 } else { - result.WriteByte(c) + buf.WriteByte(c) end += 2 } case quote: + if buf == nil { + result := ps.Input[ps.Pos+1 : end] + ps.Pos = end + 1 + return Node{Token: result} + } ps.Pos = end + 1 - return Node{Token: result.String()} + return Node{Token: buf.String()} default: r, w := utf8.DecodeRuneInString(ps.Input[end:]) - result.WriteRune(r) end += w + if buf != nil { + buf.WriteRune(r) + } } }