Improving Performance in Go - Part 1
In Go, when you're dealing with converting basic data types like integers or floats to strings or vice versa, you often have two packages available: strconv and fmt.
Now, when it comes to converting primitives to/from strings, the recommendation is to use strconv because it's tailored for these operations and is optimized for speed. It means that if your primary goal is to efficiently convert numbers to strings or strings to numbers, strconv is a better choice over fmt because it's more focused and performs these tasks more quickly.
func intToStringStrconv(i int) string {
return strconv.Itoa(i)
}
Benchmarking strconv:
664765551 1.697 ns/op
func intToStringFmt(i int) string {
return fmt.Sprintf("%d", i)
}
Benchmarking fmt:
27995788 43.26 ns/op
we can see the difference, comparatively fmt conversion took longer time than strconv.