Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently concatenate strings in go

In Go, a 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 s 

but that does not seem very efficient.

like image 600
Randy Sugianto 'Yuku' Avatar asked Nov 19 '09 03:11

Randy Sugianto 'Yuku'


People also ask

How do you concatenate strings in Go?

In Go strings, the process of adding two or more strings into a new single string is known as concatenation. The simplest way of concatenating two or more strings in the Go language is by using + operator . It is also known as a concatenation operator. str1 = "Welcome!"

How do I concatenate strings multiple times?

Or you can just take advantage of the fact that multiplying a string concatenates copies of it: add a space to the end of your string and multiply without using join . >>>

Is concatenation faster than join?

Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.


1 Answers

New Way:

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.

like image 184
marketer Avatar answered Sep 18 '22 06:09

marketer