Skip to content

Instantly share code, notes, and snippets.

@necrophonic
Last active October 3, 2022 01:36
Show Gist options
  • Save necrophonic/1ac6bacbea26139c62e71a2031af08c9 to your computer and use it in GitHub Desktop.
Save necrophonic/1ac6bacbea26139c62e71a2031af08c9 to your computer and use it in GitHub Desktop.
Manual (slightly faster, but unsafe) implementation of Atoi for converting strings into integers
package main
import (
"fmt"
"math"
)
func main() {
n := "12345"
v := 0.0
// Convert the string byte by byte
// We're not doing any error checking for pure speed so be very careful
// pre-validating your input.
// nb. If you wrap this in a function call you'll lose efficiency
//
// Benchmarked against strconv.Atoi in 3s:
//
// BenchmarkAtoi-12 469316667 7.51 ns/op
// BenchmarkManual-12 613654023 5.85 ns/op
//
for i := 0; i < len(n); i++ {
v += float64(n[i] - 48) * math.Pow10(len(n)-i-1)
}
fmt.Printf("%s -> %d\n",n,int(v))
}
@labi-le
Copy link

labi-le commented Oct 3, 2022

// cpu: AMD Ryzen 5 4500U with Radeon Graphics         
// BenchmarkFastAtoi
// BenchmarkFastAtoi-6   	443713263	         2.705 ns/op
//
func FastAtoi(s string) int {
	var val int

	for _, c := range s {
		val = val*10 + int(c-'0')
	}

	return val
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment