Extract a chain of ifs into separate func This gives a ~10% slowdown of a full test run, which is tolerable. Switch statement is still slightly slower (~5%). Using map turned out to be unacceptably slow (~3x slowdown).
Vytautas Ĺ altenis vytas@rtfb.lt
Sun, 26 Jan 2014 21:27:34 +0200
1 files changed,
22 insertions(+),
31 deletions(-)
jump to
M
html.go
→
html.go
@@ -127,45 +127,36 @@ smartypants: smartypants(flags),
} } +// Using if statements is a bit faster than a switch statement. As the compiler +// improves, this should be unnecessary this is only worthwhile because +// attrEscape is the single largest CPU user in normal use. +// Also tried using map, but that gave a ~3x slowdown. +func escapeSingleChar(char byte) (string, bool) { + if char == '"' { + return """, true + } + if char == '&' { + return "&", true + } + if char == '<' { + return "<", true + } + if char == '>' { + return ">", true + } + return "", false +} + func attrEscape(out *bytes.Buffer, src []byte) { org := 0 for i, ch := range src { - // using if statements is a bit faster than a switch statement. - // as the compiler improves, this should be unnecessary - // this is only worthwhile because attrEscape is the single - // largest CPU user in normal use - if ch == '"' { + if entity, ok := escapeSingleChar(ch); ok { if i > org { // copy all the normal characters since the last escape out.Write(src[org:i]) } org = i + 1 - out.WriteString(""") - continue - } - if ch == '&' { - if i > org { - out.Write(src[org:i]) - } - org = i + 1 - out.WriteString("&") - continue - } - if ch == '<' { - if i > org { - out.Write(src[org:i]) - } - org = i + 1 - out.WriteString("<") - continue - } - if ch == '>' { - if i > org { - out.Write(src[org:i]) - } - org = i + 1 - out.WriteString(">") - continue + out.WriteString(entity) } } if org < len(src) {