Home >Backend Development >Golang >How to Convert an Int32 to a String in Go: Which Method is Fastest?
Converting Int32 to String in Go: Beyond Int and Int64
In Go, converting an int32 to a string can be accomplished without the need for intermediate conversions to int or int64. Here are several approaches to achieve this:
1. Using fmt.Sprint(i)
s := fmt.Sprint(i)
This method provides a straightforward one-line solution.
2. Creating a Custom Conversion Function
For optimal performance, a custom conversion function can be created:
func String(n int32) string { // Implementation details return string(buf[pos:]) }
3. Using strconv.Itoa(int(i))
s := strconv.Itoa(int(i))
While this approach involves converting to int first, it offers a relatively fast solution.
4. Using strconv.FormatInt(int64(i), 10)
s := strconv.FormatInt(int64(i), 10)
This method performs faster than strconv.Itoa, as it directly converts the int32 to string.
Performance Comparison
To compare the efficiency of these methods, a benchmark was conducted with 50 million iterations:
Method | Time Taken |
---|---|
String | 5.5923198s |
String2 | 5.5923199s |
strconv.FormatInt(int64(i), 10) | 5.9133382s |
strconv.Itoa(int(i)) | 5.9763418s |
fmt.Sprint(i) | 13.5697761s |
As evident from the results, the custom conversion function String provides the fastest execution time.
The above is the detailed content of How to Convert an Int32 to a String in Go: Which Method is Fastest?. For more information, please follow other related articles on the PHP Chinese website!