Skip to content

Commit

Permalink
Merge pull request #7 from lawrencegripper/lg/sqid-perf
Browse files Browse the repository at this point in the history
Speedier `Sqids.new` 🦑
  • Loading branch information
4kimov authored Jul 25, 2024
2 parents a02f06a + 6d0e5b4 commit ae008e6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,11 @@ id = sqids.encode([1, 2, 3]) # 'se8ojk'
numbers = sqids.decode(id) # [1, 2, 3]
```

> [!WARNING]
> If you provide a large custom blocklist and/or custom alphabet, calls to `Sqid.new` can take
> ~1ms. You should create a singleton instance of `Sqid` at service start and reusing that rather than
> repeatedly calling `Squid.new`
## 📝 License

[MIT](LICENSE)
16 changes: 13 additions & 3 deletions lib/sqids.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,19 @@ def initialize(options = {})
"Minimum length has to be between 0 and #{min_length_limit}"
end

filtered_blocklist = blocklist.select do |word|
word.length >= 3 && (word.downcase.chars - alphabet.downcase.chars).empty?
end.to_set(&:downcase)
filtered_blocklist = if blocklist == DEFAULT_BLOCKLIST && alphabet == DEFAULT_ALPHABET
# If the blocklist is the default one, we don't need to filter it
# we already know it's valid (lowercase and words longer than 3 chars)
blocklist
else
# Downcase the alphabet once, rather than in the loop, to save significant time
# with large blocklists
downcased_alphabet = alphabet.downcase.chars
# Filter the blocklist
blocklist.select do |word|
word.length >= 3 && (word.downcase.chars - downcased_alphabet).empty?
end.to_set(&:downcase)
end

@alphabet = shuffle(alphabet)
@min_length = min_length
Expand Down

0 comments on commit ae008e6

Please sign in to comment.