package main
import (
"bytes"
"fmt"
)
func main() {
strings := []string{"This ", "is ", "even ",
"more ", "performant "}
buffer := bytes.Buffer{}
for _, val := range strings {
buffer.WriteString(val)
}
fmt.Println(buffer.String())
}
/*
This is even more performant
*/
package main
import (
"fmt"
)
func main() {
strings := []string{"This ", "is ", "even ",
"more ", "performant "}
bs := make([]byte, 100)
bl := 0
for _, val := range strings {
bl += copy(bs[bl:], []byte(val))
}
fmt.Println(string(bs[:]))
}
/*
This is even more performant
*/
性能测试
package bench
import (
"bytes"
"testing"
)
const testString = "test"
func BenchmarkConcat(b *testing.B) {
var str string
b.ResetTimer()
for n := 0; n < b.N; n++ {
str += testString
}
b.StopTimer()
}
func BenchmarkBuffer(b *testing.B) {
var buffer bytes.Buffer
b.ResetTimer()
for n := 0; n < b.N; n++ {
buffer.WriteString(testString)
}
b.StopTimer()
}
func BenchmarkCopy(b *testing.B) {
bs := make([]byte, b.N)
bl := 0
b.ResetTimer()
for n := 0; n < b.N; n++ {
bl += copy(bs[bl:], testString)
}
b.StopTimer()
}
go test -bench=.
goos: darwin
goarch: amd64
pkg: go_web/bench
BenchmarkConcat-8 500000 114962 ns/op
BenchmarkBuffer-8 100000000 14.8 ns/op
BenchmarkCopy-8 500000000 3.19 ns/op
PASS
ok go_web/bench 61.018s