Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stackalloc docs should discuss performance benefit of constant size #28823

Open
JamesNK opened this issue Mar 28, 2022 · 3 comments
Open

stackalloc docs should discuss performance benefit of constant size #28823

JamesNK opened this issue Mar 28, 2022 · 3 comments
Labels
doc-enhancement Improve the current content [org][type][category] dotnet-csharp/svc lang-reference/subsvc Pri2

Comments

@JamesNK
Copy link
Member

JamesNK commented Mar 28, 2022

See Twitter discussion here: https://twitter.com/EgorBo/status/1508069816275513344

tldr:

Current:

const int MaxStackLimit = 1024;
Span<byte> buffer = inputLength <= MaxStackLimit ? stackalloc byte[inputLength] : new byte[inputLength];

Slightly faster:

const int MaxStackLimit = 1024;
Span<byte> buffer = inputLength <= MaxStackLimit ? stackalloc byte[MaxStackLimit].Slice(0, inputLength) : new byte[inputLength];

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

@JamesNK
Copy link
Member Author

JamesNK commented Mar 28, 2022

cc @EgorBo

@EgorBo
Copy link
Member

EgorBo commented Mar 28, 2022

BTW, this is something we might consider optimizing in JIT as it seems the first pattern feels more natural to users

x < 100 ? localloc[x] -- JIT should be able to figure out that x is less than 100 (e.g. via assertion prop) and it makes sense to e.g. use 128 constant size limit instead.

@danielmarbach
Copy link

What's the recommendation there if you don't have the possibility to SkipLocalsInit? For larger values of MaxStackLimit always stack allocating the max could be slower due the overhead of the locals init right? At least that is what I'm seeing when switching the pattern without SkipLocalsInit in some of my tests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
doc-enhancement Improve the current content [org][type][category] dotnet-csharp/svc lang-reference/subsvc Pri2
Projects
None yet
Development

No branches or pull requests

6 participants