First up, love sqids, been using them at work for a Ruby GraphQL where the first int represents the model (having given each a unique number) and the second the row. With that we have global ID in nice short string 😍
One thing that did trip me up was the performance of Sqids.new. I saw this taking up to 10ms and averaging around 4-5ms.
In the original implementation we called Sqids.new.encode([1,2]) once for each model the GraphQL API returned and with 100 items >50% of the time for the API response was newing up Sqids. Here is the flame graph from one of those calls:

Most of this time is inside Array.select

I can repro this, not 10ms (guess havin stackprof attached slowed things down), with Benchmark.measure
irb(main):011> Benchmark.measure { Sqids.new }
=>
#<Benchmark::Tms:0x0000714023f3df70
@cstime=0.0,
@cutime=0.0,
@label="",
@real=0.003421891000471078,
@stime=0.0006750000000000089,
@total=0.0034240000000000104,
@utime=0.0027490000000000014>
This gives us around 3.4ms per run of Squid.new
For comparison encoding a Sqid takes 0.1ms
irb(main):017> s = Sqids.new
=>
#<Sqids:0x000071403df4f508
...
irb(main):018> Benchmark.measure { s.encode([1,2]) }
=>
#<Benchmark::Tms:0x000071402493e600
@cstime=0.0,
@cutime=0.0,
@label="",
@real=0.0001069290010491386,
@stime=0.0,
@total=0.00010899999999991472,
@utime=0.00010899999999991472>
irb(main):019>
The easy fix for us has been to new up Sqid.new once and reuse.
I'm going to have a quick run at whether I can improve the per now, maybe submit a PR.
If that doesn't work out, would you be up for me submitting a PR flagging folks should reuse the Sqid object not new up one on each request?
First up, love sqids, been using them at work for a Ruby GraphQL where the first int represents the model (having given each a unique number) and the second the row. With that we have global ID in nice short string 😍
One thing that did trip me up was the performance of
Sqids.new. I saw this taking up to 10ms and averaging around 4-5ms.In the original implementation we called
Sqids.new.encode([1,2])once for each model the GraphQL API returned and with 100 items >50% of the time for the API response was newing upSqids. Here is the flame graph from one of those calls:Most of this time is inside
Array.selectI can repro this, not 10ms (guess havin stackprof attached slowed things down), with
Benchmark.measureThis gives us around 3.4ms per run of
Squid.newFor comparison encoding a
Sqidtakes 0.1msThe easy fix for us has been to new up
Sqid.newonce and reuse.I'm going to have a quick run at whether I can improve the per now, maybe submit a PR.
If that doesn't work out, would you be up for me submitting a PR flagging folks should reuse the
Sqidobject not new up one on each request?