直接下结论:
bufferTest > plusTest ~= JoinTest > sprintfTest
结果如下:
sprintfTest Run time: 3.4220012s
plusTest Run time: 2.1400019s
bufferTest Run time: 997.4µs
JoinTest Run time: 2.1810023s
贴代码:
package main
import (
"bytes"
"fmt"
"strings"
"time"
)
const number = 100000
func sprintfTest() {
var s string
bT := time.Now()
for i := 0; i < number; i++ {
s = fmt.Sprintf("%s%s", s, "hello")
}
eT := time.Since(bT)
fmt.Println("sprintfTest Run time: ", eT)
}
func plusTest() {
s := ""
bT := time.Now()
for i := 0; i < number; i++ {
s = s + "hello"
}
eT := time.Since(bT)
fmt.Println("plusTest Run time: ", eT)
}
func bufferTest() {
var s bytes.Buffer
bT := time.Now()
for i := 0; i < number; i++ {
s.WriteString("hello")
}
eT := time.Since(bT)
fmt.Println("bufferTest Run time: ", eT)
}
func JoinTest() {
s := ""
bT := time.Now()
for i := 0; i < number; i++ {
s = strings.Join([]string {s, "hello"}, "")
}
eT := time.Since(bT)
fmt.Println("JoinTest Run time: ", eT)
}
func main() {
sprintfTest()
plusTest()
bufferTest()
JoinTest()
}
有疑问加站长微信联系(非本文作者)