Interview questions:
Performance optimization
How to optimize memory allocation in the following code?
func concat(strs []string) string { var s string for _, str := range strs { s += str } return s }
Examination points: immutability of string splicing, pre-allocated memory.
How to optimize objects created at high frequency?
Inspection points: life cycle management of object pools and reduce GC pressure.
answer:
In Go, there are many ways to implement string splicing, each of which has its advantages and disadvantages. Here are some common methods and their characteristics:
1. Use+
Operator
s1 := "Hello" s2 := "World" result := s1 + " " + s2
advantage:
Simple and intuitive, suitable for splicing of small strings.
shortcoming:
Each splicing generates new strings, resulting in additional memory allocation and copying, with poor performance, especially when there are a large number of splicing.
2. Use
s1 := "Hello" s2 := "World" result := ("%s %s", s1, s2)
advantage:
Supports formatting and is suitable for string stitching that needs to be formatted.
shortcoming:
Poor performance because it involves formatting and is suitable for small amounts of splicing.
3. Use
s := []string{"Hello", "World"} result := (s, " ")
advantage:
Efficient, suitable for slicing string slices, especially when large numbers of strings.
shortcoming:
You need to put the string into the slice first, which is suitable for scenarios where all strings are known.
4. Use
var buffer ("Hello") (" ") ("World") result := ()
advantage:
Efficient, suitable for frequent splicing and less memory allocation.
shortcoming:
The code is slightly lengthy.
5. Use(Go 1.10+)
var builder ("Hello") (" ") ("World") result := ()
advantage:
Efficient, suitable for frequent splicing, less memory allocation,More efficient.
shortcoming:
Only available for Go 1.10 and above.
6. Use[]byte
andappend
var b []byte b = append(b, "Hello"...) b = append(b, " "...) b = append(b, "World"...) result := string(b)
advantage:
Efficient, suitable for frequent splicing and less memory allocation.
shortcoming:
The code is a bit complicated.
Summarize
-
A small amount of splicing:use
+
or, simple and intuitive.
-
A large number of splicing:use
、
or
, better performance.
-
Frequent splicing:recommend
, best performance.
Choosing the right method can improve code performance and readability.
This is the article about the implementation method and difference comparison of golang string splicing. For more related golang string splicing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!