Note: The Listed platform will permanently shut down December 31, 2026. Your data published on Listed will still be available in your personal Standard Notes account. Learn more

Go语言中 五种字符串的 拼接方式

【1】 + 拼接方式

这种方式是我在写golang经常用的方式,go语言用 + 拼接,php使用 . 拼接,不过由于golang中的字符串是不可变的类型,因此用 + 连接会产生一个新的字符串对效率有影响。

func main() {
    s1 := "hello"
    s2 := "word"
    s3 := s1 + s2
    fmt.Print(s3) //s3 = "helloword"
}

【2】Sprintf函数

s1 := "hello"
s2 := "word"
s3 := fmt.Sprintf("%s%s", s1, s2) //s3 = "helloword"

这种方式也是开发过程中经常使用到的,这样写的好处就是不会直接产生临时字符串,但是效率好像也是不是特别高。

【3】Join函数

使用Join函数我们需要先引入strings包才能调用Join函数。Join函数会先根据字符串数组的内容,计算出一个拼接之后的长度,然后申请对应大小的内存,一个一个字符串填入,在已有一个数组的情况下,这种效率会很高,如果没有的话效率也不高。我一般用来切片转字符串使用。

s1 := "hello"
s2 := "word"
var str []string = []string{s1, s2}
s3 := strings.Join(str, "")
fmt.Print(s3)

【4】buffer.Builderbuffer.WriteString函数

s1 := "hello"
s2 := "word"
var bt bytes.Buffer
bt.WriteString(s1)
bt.WriteString(s2)
s3 := bt.String()
fmt.Println(s3)

效率比上面的高不少但是我在开发中基本上没有用过。


【5】buffer.Builder函数

s1 := "hello"
s2 := "word"
var build strings.Builder
build.WriteString(s1)
build.WriteString(s2)
s3 := build.String()
fmt.Println(s3)

官方建议使用的的拼接方式,和上面的使用方法差不多,官方建议是官方的我是小白只喜欢第一种,所以一般情况下我都是用+拼接,如果拼接的字符串比较长的话就是最后一种方式了,毕竟保命要紧。

【6】直接使用运算符

func BenchmarkAddStringWithOperator(b *testing.B) {
    hello := "hello"
    world := "world"
    for i := 0; i < b.N; i++ {
        _ = hello + "," + world
    }
}

golang 里面的字符串都是不可变的,每次运算都会产生一个新的字符串,所以会产生很多临时的无用的字符串,不仅没有用,还会给 gc 带来额外的负担,所以性能比较差


主要结论

  • 在已有字符串数组的场合,使用 strings.Join() 能有比较好的性能

  • 在一些性能要求较高的场合,尽量使用 buffer.WriteString() 以获得更好的性能

  • 性能要求不太高的场合,直接使用运算符,代码更简短清晰,能获得比较好的可读性

  • 如果需要拼接的不仅仅是字符串,还有数字之类的其他需求的话,可以考虑 fmt.Sprintf()


You'll only receive email when they publish something new.

More from 张三疯
All posts