Home >Backend Development >Golang >How to Efficiently Convert int32 to String in Golang?
Convert int32 to string in Golang
Converting int32 to string in Golang can be straightforward with a concise solution: fmt.Sprint(i). However, if this direct method is not sufficient, there are several conversion options available:
Performance benchmarks indicate that the custom conversion function (String) is the most efficient, followed by strconv.FormatInt, strconv.Itoa, and fmt.Sprint.
Here's a code snippet demonstrating the comparison:
<code class="go">package main import ( "fmt" "strconv" "time" ) func main() { var s string i := int32(-2147483648) t := time.Now() for j := 0; j < 50000000; j++ { s = String(i) //s = String2(i) // Other conversion functions can be used here } fmt.Println(time.Since(t)) fmt.Println(s) } func String(n int32) string { // Custom conversion function buf := [11]byte{} pos := len(buf) i := int64(n) signed := i < 0 if signed { i = -i } for { pos-- buf[pos], i = '0'+byte(i%10), i/10 if i == 0 { if signed { pos-- buf[pos] = '-' } return string(buf[pos:]) } } }</code>
Ultimately, the best choice depends on the specific requirements and performance constraints of your application.
The above is the detailed content of How to Efficiently Convert int32 to String in Golang?. For more information, please follow other related articles on the PHP Chinese website!