

Efficient string concatenation [full guide]
source link: https://yourbasic.org/golang/build-append-concatenate-strings-efficiently/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Efficient string concatenation [full guide]

Clean and simple string building
For simple cases where performance is a non-issue,
fmt.Sprintf
is your friend.
It’s clean, simple and fairly efficient.
s := fmt.Sprintf("Size: %d MB.", 85) // s == "Size: 85 MB."
The fmt cheat sheet lists the most common formatting verbs and flags.
High-performance string concatenationGo 1.10
A strings.Builder
is used to efficiently append strings using write methods.
- It offers a subset of the
bytes.Buffer
methods that allows it to safely avoid extra copying when converting a builder to a string. - You can use the
fmt
package for formatting since the builder implements theio.Writer
interface. - The
Grow
method can be used to preallocate memory when the maximum size of the string is known.
var b strings.Builder
b.Grow(32)
for i, p := range []int{2, 3, 5, 7, 11, 13} {
fmt.Fprintf(&b, "%d:%d, ", i+1, p)
}
s := b.String() // no copying
s = s[:b.Len()-2] // no copying (removes trailing ", ")
fmt.Println(s)
1:2, 2:3, 3:5, 4:7, 5:11, 6:13
Before Go 1.10
Use fmt.Fprintf
to print into a bytes.Buffer
.
var buf bytes.Buffer
for i, p := range []int{2, 3, 5, 7, 11, 13} {
fmt.Fprintf(&buf, "%d:%d, ", i+1, p)
}
buf.Truncate(buf.Len() - 2) // Remove trailing ", "
s := buf.String() // Copy into a new string
fmt.Println(s)
1:2, 2:3, 3:5, 4:7, 5:11, 6:13
This solution is pretty efficient but may generate some excess garbage.
For higher performance, you can try to use the append functions
in package strconv
.
buf := []byte("Size: ")
buf = strconv.AppendInt(buf, 85, 10)
buf = append(buf, " MB."...)
s := string(buf)
If the expected maximum length of the string is known, you may want to preallocate the slice.
buf := make([]byte, 0, 16)
buf = append(buf, "Size: "...)
buf = strconv.AppendInt(buf, 85, 10)
buf = append(buf, " MB."...)
s := string(buf)
Further reading
40+ practical string tips [cheat sheet]
Share:
Recommend
-
27
Java 9 brought change to the handling of Strings, namely the “indified String concatenation”. The change is in the Java bytecode that the Java 9 javac compiler outputs.
-
76
In this blog, we go down the rabbit hole of string concatenation once more to talk about the curious behavior of String conversion order in the new concatenation methods.
-
61
r/java: News, Technical discussions, research papers and assorted things of interest related to the Java programming languageNO programming help, NO learning Java related questions!
-
49
Indified String concatenation is a fantastic beast. In this post I will try to shed some light on some of the implementation details, and maybe get to why I get excited over finding some peculiar way to optimize it from time to time.
-
41
r/PHP: Ask questions about frameworks, try your hand at php golf and strike gold or simply show off your latest work.
-
40
Among the most heavily used string handling functions declared in the standard C <string.h> header are those that copy and concatenate str...
-
4
We, the PVS-Studio static code analyzer developers, have a peculiar view on beauty. On the beauty of bugs. We like to find grace in errors, examine them, try to guess how they appeared. Today we have an interesting case when the concepts of l...
-
10
CONCENTO RDG – Single Value Derivation Rule ( String Concatenation & Arithmetic Operation ) in BRF+ Concento™ Rapid Data Governance...
-
3
Doing String Concatenation With Python’s Plus Operator (+) String concatenation is a pretty common operation consisting of joining two or more strings together end to end to build a final string. Perhaps the...
-
5
Unlocking Python’s Full Potential: A Guide to Cleaner, Efficient Code " This article is part of in the series ...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK