Go: Simple optimization notes
When your VPS is running multiple service applications, but one of them sometimes takes up all the resources, making it impossible to access the server through ssh. You move to using a Kubernetes cluster and set limits for all applications. We then saw some applications being restarted as the OOM-killer fixed the memory "leak" issue.
Of course, OOM is not always a leak problem, it can also be a resource overrun. Leakage problems are most likely caused by program errors. The topic we are talking about today is how to avoid this situation as much as possible.
Excessive resource consumption can hurt the wallet, which means we need to take immediate action.
Don’t optimize prematurely
Now let’s talk about optimization. Hopefully you can understand why we shouldn’t optimize prematurely!
First, optimization may be useless work. Because we should study the entire application first, and your code will most likely not be the bottleneck. What we need is quick results, MVP (Minimum Viable Product, minimum viable product), and then we will consider its problems. #Second, optimization must have a basis. That is to say, every optimization should be based on a benchmark, and we must prove how much profit it brings us. #Third, optimization may bring complexity. What you need to know is that most optimizations make your code less readable. You need to strike this balance.
Optimization suggestions
Now we give some practical suggestions according to the standard entity classification in Go.
1. Arrays and slices
Allocate memory for slices in advance
Try to use the third parameter: <span style="font-size: 15px;"> make([]T, 0, len)</span>
If you don’t know the exact number of elements and the slice is short-lived, you can allocate a larger size to ensure that the slice does not will grow.
Don’t forget to use copy
Try not to use append when copying, such as when merging two or more slices.
Iterate correctly
For a slice containing many elements or large elements, use for to get a single element. This way unnecessary duplication will be avoided.
Multiple Slices
If some operation is performed on the incoming slice and returns a modified result, we can return it. This avoids new memory allocation.
Don't leave unused portions of the slice
If you need to cut off a small piece from the slice and use it only, the main part of the slice will also be retained. The correct approach is to use a new copy of this small slice and throw the old slice to the GC.
2. Strings
Correct splicing
If splicing strings can be completed in one statement, use <span style="font-size: 15px;"> </span>
Operator. If you need to do this in a loop, use <span style="font-size: 15px;">string.Builder</span>
, and use its <span style="font-size: 15px;">Grow</span>
Method pre-specifies the size of <span style="font-size: 15px;">Builder</span>
to reduce the number of memory allocations.
Conversion optimization
string and []byte are very similar in underlying structure, and sometimes strong conversion can be used between these two types to avoid memory allocation.
String resident
Strings can be pooled, thus helping the compiler store the same string only once.
Avoid allocation
We can use map (cascade) instead of composite keys, we can use byte slices. Try not to use the <span style="font-size: 15px;">fmt</span>
package because all its methods use reflection.
3. Structure
Avoid copying large structures
The small structure we understand is no more than 4 fields and no more than one machine word size.
Some typical copy scenes
Project to interface -
Channel reception and transmission Replace elements in the map Add elements to the slice Iterate (range)
Avoid accessing structure fields through pointers
Dereferencing is expensive and we should do it as little as possible, especially in loops. It also loses the ability to use fast registers.
Handling small structures
This work is optimized by the editor, which means it is cheap.
Use alignment to reduce structure size
We can reduce the size of a structure by aligning it (arranging them in the correct order according to the size of the fields) size itself.
4. Functions
Use inline functions or inline them yourself
Try writing small functions that can be inlined by the compiler and it will Fast, even faster than embedding the code in the function yourself. This is especially true for hot paths.
Which ones will not be inline
recovery select block Type declaration defer -
##goroutine for-range
Try to use small parameters because of their duplication will be optimized. Try to keep replication and stack growth balanced on the GC load. Avoid large numbers of parameters and let your program use fast registers (their number is limited).
Named return valuesThis seems more efficient than declaring these variables in the function body.
Save intermediate resultsHelp the compiler optimize your code, save the intermediate results, and then there will be more options to optimize your code.
Use defer carefullyTry not to use defer, or at least don't use it in a loop.
Help hot pathAvoid allocating memory in the hot path, especially for short-lived objects. Make the most common branches (if, switch)
5. MapAllocate memory in advanceSame as slice, when initializing map, specify its size .
Use empty structs as valuesstruct{} is nothing (takes up no memory), so it is very beneficial to use it when passing signals for example.
Clear map
map can only grow, not shrink. When we need to reset the map, deleting all its elements won't help.
Try not to use pointers in keys and values
If the map does not contain pointers, then the GC will not waste precious time on it. Strings also use pointers, so you should use byte arrays instead of strings as keys.
Reduce the number of modifications
Similarly, we don’t want to use pointers, but we can use a combination of map and slice, storing the keys in the map and the values in the slice. This way we can change the value without restrictions.
6. Interface
Calculate memory allocation
Remember that when you want to assign a value to an interface, you first need to copy it somewhere, Then paste the pointer to it. The key is to copy. It turns out that the cost of boxing and unboxing the interface will be approximately the same as an allocation of the struct size.
Selecting the optimal type
In some cases, there is no allocation during boxing and unboxing of an interface. For example, small or Boolean values of variables and constants, structures with one simple field, pointers (including map, channel, func)
Avoid memory allocation
As elsewhere, try to avoid unnecessary allocations. For example assigning one interface to another instead of boxing twice.
Use only when needed
Avoid using interfaces in frequently called function parameters and return results. We don't need additional unpacking operations. Reduce the frequency of using interface method calls as it prevents inlining.
7. Pointers, Channels, Bounds Checks
Avoid unnecessary dereferences
Especially in loops as it turns out to be too expensive . Dereferencing is something we don't want to do at our own expense.
Using channels is inefficient
Channel synchronization is slower than other synchronization primitive methods. In addition, the more cases in select, the slower our program will be. However, select, case plus default have been optimized.
Avoid unnecessary bounds checks
This is also expensive and we should avoid it. For example, check (get) the maximum slice index only once, not multiple times. It’s best to try getting the extreme option now.
Summary
Throughout this article, we saw some of the same optimization rules.
Help the compiler make the right decision and it will thank you. Allocate memory at compile time, use intermediate results, and try to keep your code readable.
I reiterate that for implicit optimization, benchmarks are mandatory. If something that worked yesterday won't work tomorrow because the compiler changes too quickly between versions, and vice versa.
Don’t forget to use Go’s built-in profiling and tracing tools.
The above is the detailed content of Go: Simple optimization notes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



In Go, the function life cycle includes definition, loading, linking, initialization, calling and returning; variable scope is divided into function level and block level. Variables within a function are visible internally, while variables within a block are only visible within the block.

In Go, WebSocket messages can be sent using the gorilla/websocket package. Specific steps: Establish a WebSocket connection. Send a text message: Call WriteMessage(websocket.TextMessage,[]byte("Message")). Send a binary message: call WriteMessage(websocket.BinaryMessage,[]byte{1,2,3}).

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

Go and the Go language are different entities with different characteristics. Go (also known as Golang) is known for its concurrency, fast compilation speed, memory management, and cross-platform advantages. Disadvantages of the Go language include a less rich ecosystem than other languages, a stricter syntax, and a lack of dynamic typing.

Memory leaks can cause Go program memory to continuously increase by: closing resources that are no longer in use, such as files, network connections, and database connections. Use weak references to prevent memory leaks and target objects for garbage collection when they are no longer strongly referenced. Using go coroutine, the coroutine stack memory will be automatically released when exiting to avoid memory leaks.

View Go function documentation using the IDE: Hover the cursor over the function name. Press the hotkey (GoLand: Ctrl+Q; VSCode: After installing GoExtensionPack, F1 and select "Go:ShowDocumentation").

Unit testing concurrent functions is critical as this helps ensure their correct behavior in a concurrent environment. Fundamental principles such as mutual exclusion, synchronization, and isolation must be considered when testing concurrent functions. Concurrent functions can be unit tested by simulating, testing race conditions, and verifying results.

In Golang, error wrappers allow you to create new errors by appending contextual information to the original error. This can be used to unify the types of errors thrown by different libraries or components, simplifying debugging and error handling. The steps are as follows: Use the errors.Wrap function to wrap the original errors into new errors. The new error contains contextual information from the original error. Use fmt.Printf to output wrapped errors, providing more context and actionability. When handling different types of errors, use the errors.Wrap function to unify the error types.
