Skip to content

Instantly share code, notes, and snippets.

@AlekSi
Created July 27, 2014 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlekSi/761c16f4c7c7bb6556a1 to your computer and use it in GitHub Desktop.
Save AlekSi/761c16f4c7c7bb6556a1 to your computer and use it in GitHub Desktop.
package replace
import (
"fmt"
"strings"
"testing"
)
var keys []string
func init() {
keys = make([]string, 9)
for i := 0; i < 9; i++ {
keys[i] = fmt.Sprintf("p%d", i+1)
}
}
func BenchmarkOriginal(b *testing.B) {
var res string
for i := 0; i < b.N; i++ {
res = "http://site.com/path/?p1={p1}&p2={p2}&p3={p3}&p4={p4}&p5={p5}&p6={p6}&p7={p7}&p8={p8}&p9={p9}"
for _, k := range keys {
res = strings.Replace(res, fmt.Sprintf("{%s}", k), k, 1)
}
}
if res != "http://site.com/path/?p1=p1&p2=p2&p3=p3&p4=p4&p5=p5&p6=p6&p7=p7&p8=p8&p9=p9" {
b.Fail()
}
}
func BenchmarkSimpleStrings(b *testing.B) {
var res string
for i := 0; i < b.N; i++ {
res = "http://site.com/path/?p1={p1}&p2={p2}&p3={p3}&p4={p4}&p5={p5}&p6={p6}&p7={p7}&p8={p8}&p9={p9}"
for _, k := range keys {
res = strings.Replace(res, "{"+k+"}", k, 1)
}
}
if res != "http://site.com/path/?p1=p1&p2=p2&p3=p3&p4=p4&p5=p5&p6=p6&p7=p7&p8=p8&p9=p9" {
b.Fail()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment