Created
October 22, 2013 09:33
-
-
Save naoina/7097745 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"regexp" | |
"strings" | |
"testing" | |
"unicode" | |
) | |
func BenchmarkSplitJoin(b *testing.B) { | |
b.StopTimer() | |
s := "hoge_foo_bar" | |
b.StartTimer() | |
for i := 0; i < b.N; i++ { | |
ss := strings.Split(s, "_") | |
var buf bytes.Buffer | |
for _, v := range ss { | |
buf.WriteString(strings.Title(v)) | |
buf.String() | |
} | |
} | |
} | |
func BenchmarkReplace(b *testing.B) { | |
b.StopTimer() | |
s := "hoge_foo_bar" | |
b.StartTimer() | |
for i := 0; i < b.N; i++ { | |
strings.Replace(strings.Title(strings.Replace(s, "_", " ", -1)), " ", "", -1) | |
} | |
} | |
func BenchmarkRegexp(b *testing.B) { | |
b.StopTimer() | |
s := "hoge_foo_bar" | |
r := regexp.MustCompile(`_([a-z])`) | |
fn := func(m string) string { | |
return strings.ToUpper(string(m[1])) | |
} | |
b.StartTimer() | |
for i := 0; i < b.N; i++ { | |
strings.Title(r.ReplaceAllStringFunc(s, fn)) | |
} | |
} | |
func BenchmarkForLoop(b *testing.B) { | |
b.StopTimer() | |
s := "hoge_foo_bar" | |
b.StartTimer() | |
for i := 0; i < b.N; i++ { | |
buf := make([]rune, 0, len(s)) | |
conv := false | |
for _, v := range s { | |
if v == '_' { | |
conv = true | |
continue | |
} | |
if conv { | |
buf = append(buf, unicode.ToUpper(v)) | |
conv = false | |
continue | |
} | |
buf = append(buf, v) | |
} | |
buf[0] = unicode.ToUpper(buf[0]) | |
_ = string(buf) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment