sqids / sqids-dotnet

Official .NET port of Sqids. Generate short unique IDs from numbers.

Home Page:https://sqids.org/dotnet

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A memory-alloc quesiton in the constructor of `SqidsEncoder`

LeaFrock opened this issue · comments

Sorry to interrupt you again. I have a small question: why do you use Span in the following codes ?

                // 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();

First of all, the allocation of a char array for _alphabet is unavoidable.

Then, if the alphabet size is less than MaxStackallocSize, shuffledAlphabet is allocated on the stack but the last code line converts it to a char[]. Otherwise, shuffledAlphabet.ToArray() will create another new char[] and shuffledAlphabet is going to be collected by GC, which means double allocation.

Why not just let shuffledAlphabet be a char array and assign it to _alphabet? Span seems to be unnecessary here.

You're 100% correct! Great job spotting this! Silly mistake on my part :P
I'll make a PR to fix this.