1. Do not manipulate strings with + and FMT.Sprintf

The + operation string is convenient, but it’s really slow. Using the + in Go will cause your program to run even faster than in scripting languages. If you don’t believe me, you can do a test yourself.

func TestStr(t *testing.T) {
	str := ""
	for i := 0; i < 100000; i++ {
    	str += "test"}}Copy the code

The test results

PASS: TestStr (3.32 s)

str=""
for i in range(100000):
    str+="test"
Copy the code

Test results:

~/» time python test.py

0.03s user 0.03s system 81% cpu 0.078 total

Isn’t it amazing that Go, a static language, is 100 times slower than Python on such a simple piece of code? It’s not that Go is a problem, it’s that using + to handle strings in Go is very performance consuming, and Python is supposed to be overloaded for + manipulation strings. (Javascript + manipulation strings are also fast)

The most effective way is to use buffers
strBuf := bytes.NewBufferString("")
for i := 0; i < 100000; i++ {
	strBuf.WriteString("test")}Copy the code

The results can be tested on your own and will surprise you

Some require simple combinations of two strings. Using Buffer is a bit more cumbersome. The most obvious way to combine a string is to use fmt.sprintf (). In fact, the Sprintf of FMT is also very slow, and strings.Join would be much better if there were no complex conversion output

func TestStr(t *testing.T) {
	a, b := "Hello"."world"
	for i := 0; i < 1000000; i++ {
		fmt.Sprintf("%s%s", a, b)
		//strings.Join([]string{a, b}, "")}}Copy the code

PASS: TestStr (0.29 s)

func TestStr(t *testing.T) {
	a, b := "Hello"."world"
	for i := 0; i < 1000000; i++ {
		//fmt.Sprintf("%s%s", a, b)
		strings.Join([]string{a, b}, "")}}Copy the code

PASS: TestStr (0.09 s)

It turns out that strings.Join is about 4 times faster than Sprint.

Map [string]interface{}

Let’s take a simple example

func TestData(t *testing.T) {

	for i := 0; i < 100000000; i++ {
		var a struct {
			Name string
			Age  int
		}
		a.Name = "Hello"
		a.Age = 10
	}
}
Copy the code

PASS: TestData (0.04 s)

func TestData2(t *testing.T) {

	for i := 0; i < 100000000; i++ {
		var a = map[string]interface{}{}
		a["Name"] = "Hello"
		a["Age"] = 10}}Copy the code

PASS: TestData2 (38.30 s)

Thousands of times more efficient! Temporary structs are much faster because they don’t need to dynamically allocate content at run time, and they don’t need to check indexes like a map does, when fields are known.