Created
January 27, 2015 14:20
-
-
Save soroushjp/151150683c029e816042 to your computer and use it in GitHub Desktop.
Go Benchmarking example for string concatenation. Use with `go test -bench=.`
This file contains hidden or 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 string_concat | |
import ( | |
"bytes" | |
) | |
func ConcatOperator(original *string, concat string) { | |
// This could be written as 'return *original + concat' but wanted to confirm no special | |
// compiler optimizations existed for concatenating a string to itself. | |
*original = *original + concat | |
} | |
func SelfConcatOperator(input string, n int) string { | |
output := "" | |
for i := 0; i < n; i++ { | |
ConcatOperator(&output, input) | |
} | |
return output | |
} | |
func ConcatBuffer(original *bytes.Buffer, concat string) { | |
original.WriteString(concat) | |
} | |
func SelfConcatBuffer(input string, n int) string { | |
var output bytes.Buffer | |
for i := 0; i < n; i++ { | |
ConcatBuffer(&output, input) | |
} | |
return string(output.Bytes()) | |
} |
This file contains hidden or 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 string_concat | |
import "testing" | |
const TEST_STRING = "test" | |
func benchmarkConcat(size int, SelfConcat func(string, int) string, b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
SelfConcat(TEST_STRING, size) | |
} | |
} | |
func BenchmarkConcatOperator2(b *testing.B) { benchmarkConcat(2, SelfConcatOperator, b) } | |
func BenchmarkConcatOperator10(b *testing.B) { benchmarkConcat(10, SelfConcatOperator, b) } | |
func BenchmarkConcatOperator100(b *testing.B) { benchmarkConcat(100, SelfConcatOperator, b) } | |
func BenchmarkConcatOperator1000(b *testing.B) { benchmarkConcat(1000, SelfConcatOperator, b) } | |
func BenchmarkConcatOperator10000(b *testing.B) { benchmarkConcat(10000, SelfConcatOperator, b) } | |
func BenchmarkConcatOperator100000(b *testing.B) { benchmarkConcat(100000, SelfConcatOperator, b) } | |
func BenchmarkConcatBuffer2(b *testing.B) { benchmarkConcat(2, SelfConcatBuffer, b) } | |
func BenchmarkConcatBuffer10(b *testing.B) { benchmarkConcat(10, SelfConcatBuffer, b) } | |
func BenchmarkConcatBuffer100(b *testing.B) { benchmarkConcat(100, SelfConcatBuffer, b) } | |
func BenchmarkConcatBuffer1000(b *testing.B) { benchmarkConcat(1000, SelfConcatBuffer, b) } | |
func BenchmarkConcatBuffer10000(b *testing.B) { benchmarkConcat(10000, SelfConcatBuffer, b) } | |
func BenchmarkConcatBuffer100000(b *testing.B) { benchmarkConcat(100000, SelfConcatBuffer, b) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment