snippetgoCritical
How to efficiently concatenate strings in go
Viewed 0 times
concatenateefficientlyhowstrings
Problem
In Go, a
So if I want to concatenate strings many times without knowing the length of the resulting string, what's the best way to do it?
The naive way would be:
but that does not seem very efficient.
string is a primitive type, which means it is read-only, and every manipulation of it will create a new string.So if I want to concatenate strings many times without knowing the length of the resulting string, what's the best way to do it?
The naive way would be:
var s string
for i := 0; i < 1000; i++ {
s += getShortStringFromSomewhere()
}
return sbut that does not seem very efficient.
Solution
New Way:
From Go 1.10 there is a
Old Way:
Use the
This does it in O(n) time.
From Go 1.10 there is a
strings.Builder type, please take a look at this answer for more detail.Old Way:
Use the
bytes package. It has a Buffer type which implements io.Writer. package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}
fmt.Println(buffer.String())
}This does it in O(n) time.
Code Snippets
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}
fmt.Println(buffer.String())
}Context
Stack Overflow Q#1760757, score: 1094
Revisions (0)
No revisions yet.