Skip to content

Instantly share code, notes, and snippets.

@AlekSi
Created July 27, 2014 15:04
Show Gist options
  • Select an option

  • Save AlekSi/761c16f4c7c7bb6556a1 to your computer and use it in GitHub Desktop.

Select an option

Save AlekSi/761c16f4c7c7bb6556a1 to your computer and use it in GitHub Desktop.

Revisions

  1. AlekSi created this gist Jul 27, 2014.
    44 changes: 44 additions & 0 deletions replace_test.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    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()
    }
    }