Preface
String splicing is a cliché. In Go language, common methods of splicing strings are:+
number, or usefmt
PackedSprintf
。
str1 := "a" + "b" // str1: "ab" str2 := ("%s%s", "a", "b") // str2: "ab"
The lower layer of string is not modifiable, so every time you splice a string, memory needs to be reallocated. If you need to splice strings frequently, the above two methods may have poor performance. Let's write down the pressure test code
// Use + to splice stringsfunc BenchmarkConcatStrWithPlus(b *) { str := "" for i := 0; i < ; i++ { str += "test" } } // Use Sprintf to splice stringsfunc BenchmarkConcatStrWithSprintf(b *) { str := "" for i := 0; i < ; i++ { str = ("%s%s", str, "test") } }
implement:go test -bench . -benchmem
, get the following results. This stress test result is left to compare with the optimized results below.
goos: darwin
goarch: amd64
pkg: example/string
cpu: Intel(R) Core(TM) i5-1038NG7 CPU @ 2.00GHz
BenchmarkConcatStrWithPlus-8 329544 87040 ns/op 663108 B/op 1 allocs/op
BenchmarkConcatStrWithSprintf-8 308691 160075 ns/op 1241769 B/op 4 allocs/op
PASS
ok example/string 78.604s
and
usage
Similar to the underlying layer, both use a []byte type slice to store strings. The usage is similar, zero value can be used directly.
Splice string:
var buf // Splice "a" and "b"("a") ("b") str := () // str equals "ab"
Stitching string:
var sb // Splice "a" and "b"("a") ("b") str := () // str equals "ab"
Moreover, both provide the Reset method, which is very convenient to combineuse.
the difference
It should be noted thatString()
There are still some differences in the implementation of the method, and the extractedString
Method source code comments:
// String returns the contents of the unread portion of the buffer // as a string. If the Buffer is a nil pointer, it returns "<nil>". // // To build strings more efficiently, see the type. func (b *Buffer) String() string {
ofString
The method converts the underlying []byte into a string, which requires additional memory application, but does not use it.
Performance comparison
// Use splice stringfunc BenchmarkConcatStrWithBuf(b *) { var buf for i := 0; i < ; i++ { ("test") } _ = () } // Use splice stringfunc BenchmarkConcatStrWithSb(b *) { var sb for i := 0; i < ; i++ { ("test") } _ = () }
implement:go test -bench . -benchmem
, get the following results:
BenchmarkConcatStrWithBuf-8 87914572 17.51 ns/op 16 B/op 0 allocs/op
BenchmarkConcatStrWithSb-8 278124620 9.562 ns/op 22 B/op 0 allocs/op
PASS
ok example/string 5.442s
Compared with the above pressure measurement, the difference between (22 B/op) and (16 B/op) is still very obvious in terms of memory than Sprintf (1241769 B/op) and + (663108 B/op).
The above is the detailed content of the Go library and usage and performance comparison. For more information about Go comparison, please follow my other related articles!