-
Notifications
You must be signed in to change notification settings - Fork 18.5k
Closed
Labels
Milestone
Description
Consider the following benchmark:
package escaping
import (
"html"
"strings"
"testing"
)
const noHTMLString = `Can you hear the people sing, singing the song of
angry men. It is the music of a people who will not be slaves again.`
const withHTMLString = `We're going to demand <strong>one million
dollars</strong> or we're going to threaten Earth with a "Laser".`
var escaper = strings.NewReplacer(
`&`, "&",
`'`, "'",
`<`, "<",
`>`, ">",
`"`, """,
)
func BenchmarkHtml_EscapeString_nochanges(b *testing.B) {
for i := 0; i < b.N; i++ {
html.EscapeString(noHTMLString)
}
}
func BenchmarkStrings_Replacer_nochanges(b *testing.B) {
for i := 0; i < b.N; i++ {
escaper.Replace(noHTMLString)
}
}
func BenchmarkHtml_EscapeString_changes(b *testing.B) {
for i := 0; i < b.N; i++ {
html.EscapeString(withHTMLString)
}
}
func BenchmarkStrings_Replacer_changes(b *testing.B) {
for i := 0; i < b.N; i++ {
escaper.Replace(withHTMLString)
}
}
The performance is as follows:
BenchmarkHtml_EscapeString_nochanges 500000 3912 ns/op
BenchmarkStrings_Replacer_nochanges 5000000 368 ns/op
BenchmarkHtml_EscapeString_changes 500000 4597 ns/op
BenchmarkStrings_Replacer_changes 1000000 1360 ns/op
I've written https://golang.org/cl/141930043/ to change html.EscapeString so
that it uses a replacer internally, but it needs to wait until Go 1.5 development opens.