Created
December 19, 2013 20:56
-
-
Save gkristic/8046137 to your computer and use it in GitHub Desktop.
This is a small benchmark measuring fmt.Sscanf() abilities to parse an integer, vs. strconv.ParseInt(). Run with "go test -bench=." (no quotes) and see for yourself; results are amazing... Sscanf() is 40 times slower parsing a simple integer than ParseInt().
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
BenchmarkIntParse 50000000 57.1 ns/op | |
BenchmarkIntScanf 1000000 1911 ns/op | |
BenchmarkStrScanf 1000000 1675 ns/op |
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 scanf | |
import ( | |
"fmt" | |
"strconv" | |
"testing" | |
) | |
const str = "123423434" | |
func BenchmarkIntParse(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
bn, err := strconv.ParseInt(str, 10, 0) | |
if err != nil { | |
b.Fatal(err) | |
} | |
// We convert to int just to have exactly the same result in both | |
// tests, thus benchmarking equivalent functions. I'm using the extra | |
// assignment to get rid of the "var unused" compiler error. Note, | |
// however, that only the first assignment generates an actual | |
// assembler instruction. So, there's no need to worry about skewing | |
// the test by the weird n = n. | |
n := int(bn) | |
n = n | |
} | |
} | |
func BenchmarkIntScanf(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var n int | |
if _, err := fmt.Sscanf(str, "%d", &n); err != nil { | |
b.Fatal(err) | |
} | |
} | |
} | |
func BenchmarkStrScanf(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var s string | |
if _, err := fmt.Sscanf(str, "%s", &s); err != nil { | |
b.Fatal(err) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment