go拼接字符串的方式以及性能比较

douyacun · · 792 次点击
douyacun
持续踌躇满志,间歇性做吃等死
我实际测试了一下,拼接 1-10万数字 ```go func main() { a := make([]string, 100000) for i := 1; i <= 100000; i++ { a = append(a, strconv.Itoa(i)) } fmt.Println(unsafe.Sizeof(a)) // -- 预热 fmt.Println("--- 预热") Builder(a) buffer(a) fmt.Println("--- 开始") Builder(a) buffer(a) } func buffer(a []string) { start := time.Now() var str = bytes.NewBufferString("") for _, i := range a { str.WriteString(i) } latency := time.Now().Sub(start) fmt.Printf("buffer latency: %s len: %d\n", latency, len(str.String())) } func Builder(a []string) { start := time.Now() var str = strings.Builder{} for _, i := range a { str.WriteString(i) } latency := time.Now().Sub(start) fmt.Printf("builder latency: %s len: %d\n", latency, len(str.String())) } ``` 第一次: --- 预热 builder latency: 3.25557ms len: 488895 buffer latency: 4.47419ms len: 488895 --- 开始 builder latency: 6.116895ms len: 488895 buffer latency: 6.607627ms len: 488895 第二次: --- 预热 builder latency: 3.336517ms len: 488895 buffer latency: 2.084284ms len: 488895 --- 开始 builder latency: 2.634188ms len: 488895 buffer latency: 2.930336ms len: 488895 多次测试,都是Builder快一点,@ focusonline 牛逼
#4
更多评论
亲, 你把strings.Builder放哪了.
#1
douyacun
持续踌躇满志,间歇性做吃等死
1楼 <a href="/user/focusonline" title="@focusonline">@focusonline</a> ```go type Builder struct { addr *Builder // of receiver, to detect copies by value buf []byte } ``` ```go type Buffer struct { buf []byte // contents are the bytes buf[off : len(buf)] off int // read at &amp;buf[off], write at &amp;buf[len(buf)] lastRead readOp // last read operation, so that Unread* can work correctly. } ``` 都是存储字节slice的, - Builder writeString是append到buf中,会有扩容操作, - Buffer writeString 是通过copy内存实现的 Buffer用起来更顺手
#2