From bcb12aad11b67a3a675893f659bf366536be0512 Mon Sep 17 00:00:00 2001 From: Lorenz Bauer Date: Mon, 25 Jul 2016 20:52:23 +0100 Subject: [PATCH] Use strings.Replacer instead of hand-rolled escapeString MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reduces run-time (since replacement is done via table lookup) and memory consumption (since strings that do not need replacing are returned as they are). name old time/op new time/op delta Create-4 66.9µs ± 3% 55.0µs ±12% -17.82% (p=0.008 n=5+5) name old alloc/op new alloc/op delta Create-4 19.2kB ± 0% 13.7kB ± 0% -28.44% (p=0.008 n=5+5) name old allocs/op new allocs/op delta Create-4 617 ± 0% 498 ± 0% -19.29% (p=0.008 n=5+5) --- expfmt/text_create.go | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/expfmt/text_create.go b/expfmt/text_create.go index 0bb9c14cc..1e060879e 100644 --- a/expfmt/text_create.go +++ b/expfmt/text_create.go @@ -14,7 +14,6 @@ package expfmt import ( - "bytes" "fmt" "io" "math" @@ -285,21 +284,17 @@ func labelPairsToText( return written, nil } +var ( + escape = strings.NewReplacer("\\", `\\`, "\n", `\n`) + escapeWithDoubleQuote = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`) +) + // escapeString replaces '\' by '\\', new line character by '\n', and - if // includeDoubleQuote is true - '"' by '\"'. func escapeString(v string, includeDoubleQuote bool) string { - result := bytes.NewBuffer(make([]byte, 0, len(v))) - for _, c := range v { - switch { - case c == '\\': - result.WriteString(`\\`) - case includeDoubleQuote && c == '"': - result.WriteString(`\"`) - case c == '\n': - result.WriteString(`\n`) - default: - result.WriteRune(c) - } + if includeDoubleQuote { + return escapeWithDoubleQuote.Replace(v) } - return result.String() + + return escape.Replace(v) }