Descriptionhtml: Change EscapeString to use a strings.Replacer, because it's hugely
faster.
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
Patch Set 1 #Patch Set 2 : code review 141930043: html: Change EscapeString to use a strings.Replacer, be... #Patch Set 3 : code review 141930043: html: Change EscapeString to use a strings.Replacer, be... #Patch Set 4 : code review 141930043: html: Change EscapeString to use a strings.Replacer, be... #Patch Set 5 : diff -r ca2c8c76aed9 https://code.google.com/p/go/ #Patch Set 6 : diff -r ca2c8c76aed9 https://code.google.com/p/go/ #Patch Set 7 : diff -r ca2c8c76aed9 https://code.google.com/p/go/ #
MessagesTotal messages: 8
|