在Go中,字符串是一种基本类型,这意味着它是只读的,对它的每次操作都会创建一个新字符串。

如果我想多次连接字符串而不知道结果字符串的长度,最好的方法是什么?

最天真的做法是:

var s string
for i := 0; i < 1000; i++ {
    s += getShortStringFromSomewhere()
}
return s

但这似乎不是很有效。


当前回答

我最初的建议是

s12 := fmt.Sprint(s1,s2)

但以上答案使用字节。Buffer - WriteString()是最有效的方法。

我最初的建议是使用反射和类型开关。参见(p *pp) doPrint和(p *pp) printArg 我曾经天真地认为,基本类型没有通用的Stringer()接口。

至少Sprint()内部使用bytes.Buffer。因此

`s12 := fmt.Sprint(s1,s2,s3,s4,...,s1000)`

在内存分配方面是可接受的。

Sprint()连接可用于快速调试输出。 =>否则使用bytes。缓冲……WriteString

其他回答

这是最快的解决方案,不需要 你首先需要知道或计算总的缓冲区大小:

var data []byte
for i := 0; i < 1000; i++ {
    data = append(data, getShortStringFromSomewhere()...)
}
return string(data)

根据我的基准测试,它比复制解决方案慢了20% (8.1ns / 追加而不是6.72ns),但仍然比使用bytes.Buffer快55%。

这是@cd1 (Go 1.8, linux x86_64)提供的实际版本的基准测试,修复了@icza和@PickBoy提到的错误。

字节。Buffer仅比通过+操作符直接串接快7倍。

package performance_test

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

const (
    concatSteps = 100
)

func BenchmarkConcat(b *testing.B) {
    for n := 0; n < b.N; n++ {
        var str string
        for i := 0; i < concatSteps; i++ {
            str += "x"
        }
    }
}

func BenchmarkBuffer(b *testing.B) {
    for n := 0; n < b.N; n++ {
        var buffer bytes.Buffer
        for i := 0; i < concatSteps; i++ {
            buffer.WriteString("x")
        }
    }
}

计时:

BenchmarkConcat-4                             300000          6869 ns/op
BenchmarkBuffer-4                            1000000          1186 ns/op

如果你知道你要预分配的字符串的总长度,那么最有效的连接字符串的方法可能是使用内置函数拷贝。如果你事先不知道总长度,不要抄写,而是阅读其他答案。

在我的测试中,这种方法比使用字节快3倍。Buffer,并且比使用运算符+快得多(~ 12000倍)。此外,它使用更少的内存。

我创建了一个测试用例来证明这一点,结果如下:

BenchmarkConcat  1000000    64497 ns/op   502018 B/op   0 allocs/op
BenchmarkBuffer  100000000  15.5  ns/op   2 B/op        0 allocs/op
BenchmarkCopy    500000000  5.39  ns/op   0 B/op        0 allocs/op

下面是测试代码:

package main

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

func BenchmarkConcat(b *testing.B) {
    var str string
    for n := 0; n < b.N; n++ {
        str += "x"
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); str != s {
        b.Errorf("unexpected result; got=%s, want=%s", str, s)
    }
}

func BenchmarkBuffer(b *testing.B) {
    var buffer bytes.Buffer
    for n := 0; n < b.N; n++ {
        buffer.WriteString("x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); buffer.String() != s {
        b.Errorf("unexpected result; got=%s, want=%s", buffer.String(), s)
    }
}

func BenchmarkCopy(b *testing.B) {
    bs := make([]byte, b.N)
    bl := 0

    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        bl += copy(bs[bl:], "x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); string(bs) != s {
        b.Errorf("unexpected result; got=%s, want=%s", string(bs), s)
    }
}

// Go 1.10
func BenchmarkStringBuilder(b *testing.B) {
    var strBuilder strings.Builder

    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        strBuilder.WriteString("x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); strBuilder.String() != s {
        b.Errorf("unexpected result; got=%s, want=%s", strBuilder.String(), s)
    }
}

新方法:

从Go 1.10开始,有一个字符串。建造者类型,请看看这个答案的更多细节。

老方法:

使用bytes包。它有一个实现io.Writer的Buffer类型。

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var buffer bytes.Buffer

    for i := 0; i < 1000; i++ {
        buffer.WriteString("a")
    }

    fmt.Println(buffer.String())
}

它在O(n)时间内完成。

在Go 1.10+中有字符串。构建器。

Builder用于使用Write方法有效地构建字符串。它最小化了内存复制。零值就可以使用了。


例子

这与bytes.Buffer几乎相同。

package main

import (
    "strings"
    "fmt"
)

func main() {
    // ZERO-VALUE:
    //
    // It's ready to use from the get-go.
    // You don't need to initialize it.
    var sb strings.Builder

    for i := 0; i < 1000; i++ {
        sb.WriteString("a")
    }

    fmt.Println(sb.String())
}

点击在操场上看这个。


支持的接口

StringBuilder的方法是在现有接口的基础上实现的。这样您就可以在代码中轻松地切换到新的Builder类型。

Grow(int) ->字节。缓冲#成长 Len() int ->字节。缓冲# Len Reset() ->字节。缓冲#重置 String() String -> fmt. xml斯金格 Write([]byte) (int, error) -> io。作家 WriteByte(byte)错误-> io。ByteWriter WriteRune(rune) (int, error) -> bufio。Writer#WriteRune -字节。缓冲# WriteRune WriteString(string) (int, error) -> io.stringWriter


与字节的区别。缓冲

It can only grow or reset. It has a copyCheck mechanism built-in that prevents accidentially copying it: func (b *Builder) copyCheck() { ... } In bytes.Buffer, one can access the underlying bytes like this: (*Buffer).Bytes(). strings.Builder prevents this problem. Sometimes, this is not a problem though and desired instead. For example: For the peeking behavior when the bytes are passed to an io.Reader etc. bytes.Buffer.Reset() rewinds and reuses the underlying buffer whereas the strings.Builder.Reset() does not, it detaches the buffer.


Note

不要复制StringBuilder值,因为它会缓存底层数据。 如果您想共享一个StringBuilder值,请使用指向它的指针。


更多细节请点击这里查看源代码。