-
-
Save songrgg/40bd7517e208c970403db447d3da8baa to your computer and use it in GitHub Desktop.
Golang performance benchmark sample code
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 ( | |
"strings" | |
) | |
func replaceChar1(str string, ch, replaceCh byte) string { | |
var result string | |
for i := 0; i < len(str); i++ { | |
if str[i] == ch { | |
result = result + string(replaceCh) | |
} else { | |
result = result + string(result[i]) | |
} | |
} | |
return result | |
} | |
func replaceChar2(str string, ch, replaceCh byte) string { | |
bytes := []byte(str) | |
for i := 0; i < len(str); i++ { | |
if bytes[i] == ch { | |
bytes[i] = replaceCh | |
} | |
} | |
return string(bytes) | |
} | |
func replaceChar3(str string, ch, replaceCh byte) string { | |
var strBuilder strings.Builder | |
strBuilder.Grow(len(str)) | |
for i := 0; i < len(str); i++ { | |
if str[i] == ch { | |
strBuilder.WriteByte(replaceCh) | |
} else { | |
strBuilder.WriteByte(str[i]) | |
} | |
} | |
return strBuilder.String() | |
} | |
func main() { | |
} |
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 ( | |
"strings" | |
"testing" | |
) | |
func generateString(n int) string { | |
var b strings.Builder | |
b.Grow(n) | |
for i := 0; i < n; i++ { | |
b.WriteRune('a') | |
} | |
return b.String() | |
} | |
func BenchmarkStringReplace1(b *testing.B) { | |
n := 100_000 | |
str := generateString(n) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
replaceChar1(str, 'a', 'b') | |
} | |
} | |
func BenchmarkStringReplace2(b *testing.B) { | |
n := 100_000 | |
str := generateString(n) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
replaceChar2(str, 'a', 'b') | |
} | |
} | |
func BenchmarkStringReplace3(b *testing.B) { | |
n := 100_000 | |
str := generateString(n) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
replaceChar3(str, 'a', 'b') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment