Golang 字串拼裝方式效能對比

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Go語言中字串的拼裝方法很多,那麼問題來了,到底哪家效能好?

下面代碼,分別比較了 fmt.Sprintfstring +strings.Joinbytes.Buffer,方法是迴圈若干次比較總時間。在VMWare下的Ubuntu 14.04下啟動並執行結果如下,僅供參考:

  • fmt.Sprintfstrings.Join 速度相當
  • string + 比上述二者快一倍
  • bytes.Buffer又比上者快約400-500倍
  • 如果迴圈內每次都臨時聲明一個bytes.Buffer來使用,會比持續存在慢50%,但是仍然很快

測試代碼如下:

package mainimport (    "bytes"    "fmt"    "strings"    "time")func benchmarkStringFunction(n int, index int) (d time.Duration) {    v := "ni shuo wo shi bu shi tai wu liao le a?"    var s string    var buf bytes.Buffer    t0 := time.Now()    for i := 0; i < n; i++ {        switch index {        case 0: // fmt.Sprintf            s = fmt.Sprintf("%s[%s]", s, v)        case 1: // string +            s = s + "[" + v + "]"        case 2: // strings.Join            s = strings.Join([]string{s, "[", v, "]"}, "")        case 3: // temporary bytes.Buffer            b := bytes.Buffer{}            b.WriteString("[")            b.WriteString(v)            b.WriteString("]")            s = b.String()        case 4: // stable bytes.Buffer            buf.WriteString("[")            buf.WriteString(v)            buf.WriteString("]")        }        if i == n-1 {            if index == 4 { // for stable bytes.Buffer                s = buf.String()            }            fmt.Println(len(s)) // consume s to avoid compiler optimization        }    }    t1 := time.Now()    d = t1.Sub(t0)    fmt.Printf("time of way(%d)=%v\n", index, d)    return d}func main() {    k := 5    d := [5]time.Duration{}    for i := 0; i < k; i++ {        d[i] = benchmarkStringFunction(10000, i)    }    for i := 0; i < k-1; i++ {        fmt.Printf("way %d is %6.1f times of way %d\n", i, float32(d[i])/float32(d[k-1]), k-1)    }}

其中一次的結果如下:

410000time of way(0)=1.199641573s410000time of way(1)=568.716669ms410000time of way(2)=1.197077483s41time of way(3)=2.277063ms410000time of way(4)=1.398864msway 0 is  857.6 times of way 4way 1 is  406.6 times of way 4way 2 is  855.7 times of way 4way 3 is    1.6 times of way 4

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.