This article will share with you two efficient tips in Go language: one is not to use fmt.Sprintf to operate strings; the other is to use temporary Struct instead of key-value pairs for fixed fields. map[string]interface{}.
It is very convenient to operate strings, but it is really slow. Using it in Go language will cause your program to run faster than the script. The language is still full. If you don’t believe it, you can do a test by yourself. Use operations and iterate 100,000 times. Python and Javascript are much faster than Go (a lot, not a little)
func TestStr(t *testing.T) { str := "" for i := 0; i < 100000; i++ { str += "test" } }
Test results
PASS: TestStr (3.32s)
str="" for i in range(100000): str+="test"
Test results:
~/» time python test.py
0.03s user 0.03s system 81% cpu 0.078 total
As a static language, Go's execution efficiency on such a simple piece of code is 100 times slower than that of Python. Isn't it incredible? It's not a problem with Go, but using string processing in Go is very performance-intensive, and Python should have overloaded optimizations for operating strings. (Javascript also operates strings very quickly)
Related tutorials: go video tutorial
strBuf := bytes.NewBufferString("") for i := 0; i < 100000; i++ { strBuf.WriteString("test") }
You can test the results by yourself, you will be surprised
Some need to simply combine two strings, using Buffer is a bit more troublesome, the easier thing to think of is to use fmt.Sprintf() to combine , the source code in many packages is also written in this way. In fact, fmt's Sprintf is also very slow. If there is no complex type conversion output, the performance of using strings.Join will be much higher
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}, "") } }
PASS: TestStr (0.29s)
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}, "") } }
PASS: TestStr (0.09s)
Judging from the results, strings.Join is about 4 times faster than using Sprint.
Give 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 } }
PASS: TestData (0.04s)
func TestData2(t *testing.T) { for i := 0; i < 100000000; i++ { var a = map[string]interface{}{} a["Name"] = "Hello" a["Age"] = 10 } }
PASS: TestData2 (38.30s)
The efficiency is thousands of times different!
When the fields are known, using temporary Struct does not require dynamic allocation of content during runtime, and there is no need to check the index like map, so the speed will be much faster.
The above is the detailed content of Two efficient tips in Go language. For more information, please follow other related articles on the PHP Chinese website!