Skip to content

Commit

Permalink
Remove unnecessary allocation for alphabet shuffling in constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
aradalvand committed Sep 13, 2023
1 parent f40e66f commit cc79e76
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions src/Sqids/SqidsEncoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,8 @@ public SqidsEncoder(SqidsOptions options)
);
_blockList = options.BlockList.ToArray(); // NOTE: Arrays are faster to iterate than HashSets, so we construct an array here.

// TODO: `sizeof(T)` doesn't work, so we resorted to `sizeof(long)`, but ideally we should get it to work somehow — see https://github.com/sqids/sqids-dotnet/pull/15#issue-1872663234
Span<char> shuffledAlphabet = options.Alphabet.Length * sizeof(long) > MaxStackallocSize // NOTE: We multiply the number of characters by the size of a `char` to get the actual amount of memory that would be allocated.
? new char[options.Alphabet.Length]
: stackalloc char[options.Alphabet.Length];
options.Alphabet.AsSpan().CopyTo(shuffledAlphabet);
ConsistentShuffle(shuffledAlphabet);
_alphabet = shuffledAlphabet.ToArray();
_alphabet = options.Alphabet.ToArray();
ConsistentShuffle(_alphabet);
}

/// <summary>
Expand Down Expand Up @@ -210,7 +205,8 @@ private string Encode(ReadOnlySpan<int> numbers, int increment = 0)
offset = (numbers.Length + offset) % _alphabet.Length;
offset = (offset + increment) % _alphabet.Length;

Span<char> alphabetTemp = _alphabet.Length * sizeof(char) > MaxStackallocSize
// TODO: `sizeof(T)` doesn't work, so we resorted to `sizeof(long)`, but ideally we should get it to work somehow — see https://github.com/sqids/sqids-dotnet/pull/15#issue-1872663234
Span<char> alphabetTemp = _alphabet.Length * sizeof(char) > MaxStackallocSize // NOTE: We multiply the number of characters by the size of a `char` to get the actual amount of memory that would be allocated.
? new char[_alphabet.Length]
: stackalloc char[_alphabet.Length];
var alphabetSpan = _alphabet.AsSpan();
Expand Down

0 comments on commit cc79e76

Please sign in to comment.