1. 程式人生 > >string 中的一些優化事項

string 中的一些優化事項

style mic 運行 code test div light bench pre

1.1 fmt vs "+" (無轉義)

import (
    "testing"
    "fmt"
)

var (
    str = "hello gohpers!"
    sep = ","
)

func BenchmarkFmt(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ = fmt.Sprint("%s%s%s%s%s", str, sep, str, sep, str)
    }
}

func BenchmarkPlus(b *testing.B) {
    for i := 0; i < b.N; i++ {
        _ 
= str + sep + str + sep + str } }

運行結果概括如下:

BenchmarkFmt        3000000	       490 ns/op
BenchmarkPlus        15000000	        78 ns/op

1.1 fmt vs "+" (帶有轉義)

2. strings.join VS "+"

持續更新中

string 中的一些優化事項