Golang笔记

golang 几种常见的字符串连接性能比较

golang 几种常见的字符串连接性能比较

package main

import (
    "bytes"
    "fmt"
    "strings"
    "time"
)

var way map[int]string

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: // stable bytes.Buffer
            buf.WriteString("[")
            buf.WriteString(v)
            buf.WriteString("]")
        }

    }
    d = time.Since(t0)
    if index == 3 {
        s = buf.String()
    }
    fmt.Printf("string len: %d\t", len(s))
    fmt.Printf("time of [%s]=\t %v\n", way[index], d)
    return d
}

func main() {
    way = make(map[int]string, 5)
    way[0] = "fmt.Sprintf"
    way[1] = "+"
    way[2] = "strings.Join"
    way[3] = "bytes.Buffer"

    k := 4
    d := [5]time.Duration{}
    for i := 0; i < k; i++ {
        d[i] = benchmarkStringFunction(10000, i)
    }
}

摘自 https://gocn.io/question/265 5

比较结果:

string len: 410000	time of [fmt.Sprintf]=	 318.093256ms
string len: 410000	time of [+]=	 197.03476ms
string len: 410000	time of [strings.Join]=	 439.952002ms
string len: 410000	time of [bytes.Buffer]=	 435.764µs

下面这种测试更合乎逻辑,避免io:

package main

import(
    "bytes"
    "fmt"
    "strings"
    "testing"
)

var (
    strs = []string{
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
        "ten",
    }
)

func TestStringsJoin(b *testing.B) {
    for i := 0; i < b.N; i++ {
        strings.Join(strs, "")
    }
}

func TestStringsPlus(b *testing.B) {
    for i := 0; i < b.N; i++ {
        var s string
        for j := 0; j < len(strs); j++ {
            s += strs[j]
        }
    }
}

func TestBytesBuffer(b *testing.B) {
    for i := 0; i < b.N; i++ {
        var b bytes.Buffer
        for j := 0; j < len(strs); j++ {
            b.WriteString(strs[j])
        }
    }
}

func main() {
    fmt.Println("strings.Join:")
    fmt.Println(testing.Benchmark(TestStringsJoin))
    fmt.Println("bytes.Buffer:")
    fmt.Println(testing.Benchmark(TestBytesBuffer))
    fmt.Println("+:")
    fmt.Println(testing.Benchmark(TestStringsPlus))
}

结果:

strings.Join:
10000000	       139 ns/op
bytes.Buffer:
10000000	       166 ns/op
+:
 3000000	       429 ns/op
本文网址: https://golangnote.com/topic/148.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles