Skip to content

Example issue in stackalloc docs page #54665

Description

@DimucaTheDev

Type of issue

Typo

Description

In the first stackalloc example (using length), we allocate only the required amount of bytes(link):

int length = 1000;
Span<byte> buffer = length <= 1024 ? stackalloc byte[length] : new byte[length];

However, the second example(link) utilizes a constant value (MaxStackLimit). Even if inputLength is significantly less than MaxStackLimit, it will still allocate the full MaxStackLimit bytes on the stack, rather than just inputLength:

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

If using a constant size here is intended as a micro-optimization for the JIT compiler(correct me if I'm wrong), I think this nuance should be explicitly remarked on the documentation page to avoid confusing readers about actual memory allocation.

Page URL

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/stackalloc

Content source URL

https://github.com/dotnet/docs/blob/main/docs/csharp/language-reference/operators/stackalloc.md

Document Version Independent Id

f77588b3-9b31-f8ce-fad5-bf937337eb8c

Platform Id

887417a9-28b8-1821-52ae-ea7b0ba5c8e3

Article author

@BillWagner

Metadata

  • ID: ecde487e-96e5-85c2-ff87-227994f705ad
  • PlatformId: 887417a9-28b8-1821-52ae-ea7b0ba5c8e3
  • Service: dotnet-csharp
  • Sub-service: lang-reference

Related Issues

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions