Member-only story

A few tips for quickly optimizing Golang code

Beck Moulton
4 min readMay 23, 2024

--

This article will provide some code optimization guidelines, hoping to help developers enhance their program performance and simplify development, achieve more efficient and robust coding, and unlock the potential of Golang applications. Below are some useful and universal code snippets randomly selected from my commonly used practical libraries for development.

Tracking Execution Time

If you want to track the execution time of a function in Go, there is a simple and efficient trick: just use the defer keyword to implement one line of code. You only need one TrackTime function:

func TrackTime(pre time.Time) time.Duration {
elapsed := time.Since(pre)
fmt.Println("elapsed:", elapsed) return elapsed
}func TestTrackTime(t *testing.T) {
defer TrackTime(time.Now()) // <--- THIS time.Sleep(500 * time.Millisecond)
}// elapsed: 501.11125ms

Pre-allocated slices

Pre-allocating slices or maps can significantly improve Go’s performance.

We can use pre-allocated zero-length slices without specifying the length of the array. We can use append to manipulate the slices.

// 不推荐
a := make([]int, 10)
a[0] = 1// 推荐用法
b := make([]int, 0, 10)
b = append(b, 1)

Chain call

The technique of chaining calls can be applied to functions (pointers) with receivers. To illustrate this point, first write a Person structure…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

Responses (1)