Last active
October 3, 2022 01:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
commented
Oct 3, 2022
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment