Created
May 19, 2016 09:10
-
-
Save ktrysmt/b870d9d7d7dae2dbbf263def92293e79 to your computer and use it in GitHub Desktop.
結局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 main | |
import ( | |
"bytes" | |
"fmt" | |
"testing" | |
) | |
var m = [...]string{ | |
"AAAAAAAAA", | |
"AAAAAAAAA", | |
"AAAAAAAAA", | |
"AAAAAAAAA", | |
"AAAAAAAAA", | |
"AAAAAAAAA", | |
"AAAAAAAAA", | |
} | |
func BenchmarkSprintf(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = fmt.Sprintf("%s", m) | |
} | |
} | |
func BenchmarkCapBytesBuffer(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var m2 = bytes.NewBuffer(make([]byte, 0, 100)) | |
for _, v := range m { | |
m2.WriteString(v) | |
} | |
_ = m2.String() | |
} | |
} | |
func BenchmarkCapByteArray(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var m2 = make([]byte, 0, 100) | |
for _, v := range m { | |
m2 = append(m2, v...) | |
} | |
_ = string(m2) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
手元のMacBookProでとりあえず計測
結果、やっぱりキャパシティ付きのByte型appendが最速