sqids / sqids-go

Official Go port of Sqids. Generate short unique IDs from numbers.
https://sqids.org/go
MIT License
492 stars 8 forks source link

test: Add BenchmarkEncodeDecode #9

Closed peterhellberg closed 10 months ago

peterhellberg commented 11 months ago

Initial benchmarking of sqids.Encode and sqids.Decode for the input []uint64{1, 2, 3, 4, 5} on my particular machine gives me these numbers:

$ time go test -bench=. -run=BenchmarkEncodeDecode -benchmem -cpuprofile profile.out
goos: linux
goarch: amd64
pkg: github.com/sqids/sqids-go
cpu: Intel(R) Core(TM) i7-10700T CPU @ 2.00GHz
BenchmarkEncodeDecode-16           12253         97055 ns/op       32470 B/op        124 allocs/op
PASS
ok      github.com/sqids/sqids-go   2.214s

real    0m2.370s
user    0m2.299s
sys 0m0.175s

pprof shows us that a lot of unnecessary time is spent in dealing with a regular expression: pprof001

[!Note] (Re-)Compilation (and usage) of regular expressions are pretty slow in Go, so should be avoided if possible.

peterhellberg commented 11 months ago

With the change in 4e29f28 the benchmark output on my machine change to:

$ time go test -bench=. -run=BenchmarkEncodeDecode -benchmem -cpuprofile profile.out
goos: linux
goarch: amd64
pkg: github.com/sqids/sqids-go
cpu: Intel(R) Core(TM) i7-10700T CPU @ 2.00GHz
BenchmarkEncodeDecode-16           27223         42703 ns/op       31474 B/op        115 allocs/op
PASS
ok      github.com/sqids/sqids-go   1.810s

real    0m2.017s
user    0m1.986s
sys 0m0.199s

So a difference of 97055 ns/op to 42703 ns/op

And now pprof shows us that more time is spent in shuffle than in isBlockedID pprof002

4kimov commented 11 months ago

Whoa. Nice 💪

peterhellberg commented 11 months ago

@4kimov Is it cool if I merge PRs or do you want the final say in what is going into the library?

4kimov commented 11 months ago

@peterhellberg No, I'm cool with you merging, I trust your best judgement.