Created
February 25, 2015 14:31
-
-
Save phemmer/d9e18ec78f7ad2dbec0f to your computer and use it in GitHub Desktop.
string concat benchmark
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 ( | |
"fmt" | |
"testing" | |
) | |
const str = "s" | |
var bslice = []byte(str) | |
func BenchmarkByteSliceGrow(b *testing.B) { | |
var bs []byte | |
for n := 0; n < b.N; n++ { | |
bs = append(bs, bslice...) | |
} | |
} | |
func BenchmarkStringConcatGrow(b *testing.B) { | |
strAppend := "" | |
for n := 0; n < b.N; n++ { | |
strAppend += str | |
} | |
} | |
func BenchmarkFmtSprintfGrow(b *testing.B) { | |
strFmt := "" | |
for n := 0; n < b.N; n++ { | |
strFmt = fmt.Sprintf("%s%s", strFmt, str) | |
} | |
} | |
func BenchmarkByteSliceDiscard(b *testing.B) { | |
var bs []byte | |
for n := 0; n < b.N; n++ { | |
_ = append(bs, bslice...) | |
} | |
} | |
func BenchmarkStringConcatDiscard(b *testing.B) { | |
strAppend := "" | |
for n := 0; n < b.N; n++ { | |
_ = strAppend + str | |
} | |
} | |
func BenchmarkFmtSprintfDiscard(b *testing.B) { | |
strFmt := "" | |
for n := 0; n < b.N; n++ { | |
_ = fmt.Sprintf("%s%s", strFmt, str) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment