I have begun learning Go lang recently. I chose Go lang because of performance issues and Its syntax and abilities took my attention. So I read documents and watched videos on YT and Udemy, and I began coding my first project. However, I was disappointed after a while since its performance and ability of handling massive data was not near what I expected, and I started to search the reason of the lack of performance.
Eventually, I found it. There was a lot of malformed data in my test case and my application must have handle them and return an error. The point that I struggled is exactly here because I used
Errorf
function of fmt
package to return errors. Although this function provides us a lot of functionality such as formatting error message with parameters, it costs a lot. Lucky I do not need functionality fmt.Errorf
serves because I return just same error string for those malformed data. After a short searching, I found errors package and read comparison blog posts between it and fmt.Errorf
function. In the blog posts I read, errors.New
is showed as obviously faster than fmt.Errorf
, but I still wanted to see how fast it is and I wrote the code below. You can see the result at the end of the code.
errors.New ROCKS!!
Code:
package main
import (
"errors"
"fmt"
"time"
)
func testErrors() error {
return errors.New("test errors package")
}
func testFmt() error {
return fmt.Errorf("test fmt package")
}
func main() {
repeat := 100000000
start := time.Now()
for i := 0; i < repeat; i++ {
testErrors()
}
duration := time.Since(start)
fmt.Println("errors.New", duration)
start = time.Now()
for i := 0; i < repeat; i++ {
testFmt()
}
duration = time.Since(start)
fmt.Println("fmt.Errorf", duration)
}
Results:
errors.New 30.747008ms
fmt.Errorf 9.083900989s
As you can see error.News
is almost 300 times faster than fmt.Errorf
CPU and RAM I tested at:
CPU: Intel(R) Core(TM) i7-7600U CPU @ 2.80GHz
RAM: 24GB (16+8) DDR4