Skip to content

Commit

Permalink
Avoid overwriting references from users
Browse files Browse the repository at this point in the history
We now also avoid removal from the HashSet giving a small perf boost
  • Loading branch information
Genbox committed Jan 21, 2024
1 parent ff3505c commit 4b93969
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions src/Sqids/SqidsEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,21 +96,27 @@ public SqidsEncoder(SqidsOptions options)
_minLength = options.MinLength;

// NOTE: Cleanup the blocklist:
options.BlockList = new HashSet<string>(
options.BlockList,
HashSet<string> blockList = new HashSet<string>(
StringComparer.OrdinalIgnoreCase // NOTE: Effectively removes items that differ only in casing — leaves one version of each word casing-wise which will then be compared against the generated IDs case-insensitively
);
options.BlockList.RemoveWhere(w =>
// NOTE: Removes words that are less than 3 characters long
w.Length < 3 ||
// NOTE: Removes words that contain characters not found in the alphabet

foreach (string w in options.BlockList)
{
if (
// NOTE: Removes words that are less than 3 characters long
w.Length < 3 ||
// NOTE: Removes words that contain characters not found in the alphabet
#if NETSTANDARD2_0
w.Any(c => options.Alphabet.IndexOf(c.ToString(), StringComparison.OrdinalIgnoreCase) == -1) // NOTE: A `string.Contains` overload with `StringComparison` didn't exist prior to .NET Standard 2.1, so we have to resort to `IndexOf` — see https://stackoverflow.com/a/52791476
w.Any(c => options.Alphabet.IndexOf(c.ToString(), StringComparison.OrdinalIgnoreCase) == -1)) // NOTE: A `string.Contains` overload with `StringComparison` didn't exist prior to .NET Standard 2.1, so we have to resort to `IndexOf` — see https://stackoverflow.com/a/52791476
#else
w.Any(c => !options.Alphabet.Contains(c, StringComparison.OrdinalIgnoreCase))
w.Any(c => !options.Alphabet.Contains(c, StringComparison.OrdinalIgnoreCase)))
#endif
);
_blockList = [.. options.BlockList]; // NOTE: Arrays are faster to iterate than HashSets, so we construct an array here.
continue;

blockList.Add(w);
}

_blockList = blockList.ToArray(); // NOTE: Arrays are faster to iterate than HashSets, so we construct an array here.

_alphabet = options.Alphabet.ToCharArray();
ConsistentShuffle(_alphabet);
Expand Down

0 comments on commit 4b93969

Please sign in to comment.