In this article we are going to check the performance of these methods, which method is fast and which is the slowest for converting Int to String in Golang, and how we are going to do that, we are going to check the benchmark results of each method for two values one is low value and second is high value, 45(small) and 8976497664(big) like something.
Below is the benchmark code and that code we've all three ways into their separate functions.
Code is stored in main_test.go file
package main
import (
"fmt"
"strconv"
"testing"
)
var smallInt = 40
var bigInt = 999999999999999
func Itoa(s int) string {
i := strconv.Itoa(s)
return i
}
func FormatInt(s int) string {
i := strconv.FormatInt(int64(s), 10)
return i
}
func Sprintf(s int) string {
i := fmt.Sprintf("%d", s)
return i
}
func BenchmarkItoa(b *testing.B) {
for i := 0; i < b.N; i++ {
Itoa(smallInt)
}
}
func BenchmarkFormatInt(b *testing.B) {
for i := 0; i < b.N; i++ {
FormatInt(smallInt)
}
}
func BenchmarkSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
Sprintf(smallInt)
}
}
func BenchmarkItoaBig(b *testing.B) {
for i := 0; i < b.N; i++ {
Itoa(bigInt)
}
}
func BenchmarkFormatIntBig(b *testing.B) {
for i := 0; i < b.N; i++ {
FormatInt(bigInt)
}
}
func BenchmarkSprintfBig(b *testing.B) {
for i := 0; i < b.N; i++ {
Sprintf(bigInt)
}
}
We have smallInt and bigInt variable which have their corresponding values, as well we have three function as mentioned above Itoa, FormatInt, and Sprintf in which we are just trying to convert provided int value to string and returning back the string.
If you look at the code we have two functions for each Benchmark, because we want to test these functions for small and big values.
Now let's see the results of these outputs and you'll know which works faster compared to other.
As you can see fmt.Sprint is the slowest way to convert small and big int to string, and on the other hand strconv.FormatInt is the fastest way to convert a int to string , strconv,Itoa is the second fastest way almost near to strconv.FormatInt.
So hence prove that for either small or big always use strconv.FormatInt or strconv.Itoa, instead of using fmt.Sprintf.
Now one thing comes in mind why fmt.Sprintf is not fast like others, because fmt.Sprintf() uses the reflect package and reflect package works on runtime which makes it slower than strconv.Itoa() and strconv.FormatInt() functions
This article is originally posted on programmingeeksclub.com
My Personal Blogging Website : Programming Geeks Club
My Facebook Page : Programming Geeks Club
My Telegram Channel : Programming Geeks Club
My Twitter Account : Kuldeep Singh
My Youtube Channel: Programming Geeks Club
Top comments (0)