Last active
July 23, 2024 19:31
-
-
Save dtjm/c6ebc86abe7515c988ec to your computer and use it in GitHub Desktop.
Benchmarking various ways of concatenating strings in Go
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 join | |
import ( | |
"fmt" | |
"strings" | |
"testing" | |
) | |
var ( | |
testData = []string{"a", "b", "c", "d", "e"} | |
) | |
func BenchmarkJoin(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
s := strings.Join(testData, ":") | |
_ = s | |
} | |
} | |
func BenchmarkSprintf(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
s := fmt.Sprintf("%s:%s:%s:%s:%s", testData[0], testData[1], testData[2], testData[3], testData[4]) | |
_ = s | |
} | |
} | |
func BenchmarkConcat(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
s := testData[0] + ":" + testData[1] + ":" + testData[2] + ":" + testData[3] + ":" + testData[4] | |
_ = s | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use the code from @RezaOptic above
Results