Skip to content

Instantly share code, notes, and snippets.

@DarkGL
Created April 26, 2025 08:51
Show Gist options
  • Save DarkGL/091a5e3fb64fb71def01b27cac1c7d6d to your computer and use it in GitHub Desktop.
Save DarkGL/091a5e3fb64fb71def01b27cac1c7d6d to your computer and use it in GitHub Desktop.
Golang Fast: Converting 9-Digit Integers to Bytes Benchmark
package benchmark
import (
"strconv"
"testing"
)
var resultSink []byte
func BenchmarkConvertIntToString(b *testing.B) {
integerVal := 151795072
for i := 0; i < b.N; i++ {
stringByteVal := []byte(strconv.Itoa(integerVal))
resultSink = stringByteVal
}
}
func BenchmarkConvertIntToStringAppend(b *testing.B) {
integerVal := int64(151795072)
for i := 0; i < b.N; i++ {
var stringByteVal []byte
stringByteVal = strconv.AppendInt(stringByteVal, integerVal, 10)
resultSink = stringByteVal
}
}
func writeFixedIntToBuffer(n int, buf []byte) {
// Direct conversion for a fixed 9-digit positive number
buf[8] = byte('0' + n%10)
n /= 10
buf[7] = byte('0' + n%10)
n /= 10
buf[6] = byte('0' + n%10)
n /= 10
buf[5] = byte('0' + n%10)
n /= 10
buf[4] = byte('0' + n%10)
n /= 10
buf[3] = byte('0' + n%10)
n /= 10
buf[2] = byte('0' + n%10)
n /= 10
buf[1] = byte('0' + n%10)
n /= 10
buf[0] = byte('0' + n%10)
}
func BenchmarkConvertIntToStringCustom(b *testing.B) {
integerVal := 151795072
for i := 0; i < b.N; i++ {
stringByteVal := make([]byte, 9)
writeFixedIntToBuffer(integerVal, stringByteVal)
resultSink = stringByteVal
}
}
func BenchmarkConvertIntToStringReuseVar(b *testing.B) {
integerVal := 151795072
stringByteVal := make([]byte, 9)
for i := 0; i < b.N; i++ {
copy(stringByteVal, []byte(strconv.Itoa(integerVal)))
resultSink = stringByteVal
}
}
func BenchmarkConvertIntToStringCustomReuseBuffer(b *testing.B) {
integerVal := 151795072
stringByteVal := make([]byte, 9)
for i := 0; i < b.N; i++ {
writeFixedIntToBuffer(integerVal, stringByteVal)
resultSink = stringByteVal
}
}
/*
BenchmarkConvertIntToString-32 39900381 28.99 ns/op 32 B/op 2 allocs/op
BenchmarkConvertIntToStringAppend-32 58533729 20.73 ns/op 16 B/op 1 allocs/op
BenchmarkConvertIntToStringCustom-32 71037862 16.27 ns/op 16 B/op 1 allocs/op
BenchmarkConvertIntToStringReuseVar-32 65780457 18.04 ns/op 16 B/op 1 allocs/op
BenchmarkConvertIntToStringCustomReuseBuffer-32 146857864 8.182 ns/op 0 B/op 0 allocs/op
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment