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).
This commit is contained in:
Vytautas Šaltenis 2014-01-26 21:27:34 +02:00
parent 31a96c6ce7
commit cc0d56d092

53
html.go
View File

@ -127,45 +127,36 @@ func HtmlRenderer(flags int, title string, css string) Renderer {
} }
} }
// 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 "&lt;", true
}
if char == '>' {
return "&gt;", true
}
return "", false
}
func attrEscape(out *bytes.Buffer, src []byte) { func attrEscape(out *bytes.Buffer, src []byte) {
org := 0 org := 0
for i, ch := range src { for i, ch := range src {
// using if statements is a bit faster than a switch statement. if entity, ok := escapeSingleChar(ch); ok {
// 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 i > org { if i > org {
// copy all the normal characters since the last escape // copy all the normal characters since the last escape
out.Write(src[org:i]) out.Write(src[org:i])
} }
org = i + 1 org = i + 1
out.WriteString("&quot;") out.WriteString(entity)
continue
}
if ch == '&' {
if i > org {
out.Write(src[org:i])
}
org = i + 1
out.WriteString("&amp;")
continue
}
if ch == '<' {
if i > org {
out.Write(src[org:i])
}
org = i + 1
out.WriteString("&lt;")
continue
}
if ch == '>' {
if i > org {
out.Write(src[org:i])
}
org = i + 1
out.WriteString("&gt;")
continue
} }
} }
if org < len(src) { if org < len(src) {