Skip to content

Example issue in stackalloc docs page #54665

Closed

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

Activity

  1. BillWagner commented on Jul 8, 2026

    @BillWagner
    Member

    The issue here is that the second example should allocate only the required number of bytes:

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

    Note the inputLength instead of MaxStackLimit in the true arm of the conditional expression.

  2. added
    help wantedGood for community contributors to help [up-for-grabs]
    and removed on Jul 8, 2026
  3. Kira-NT commented on Sep 19, 2026

    @Kira-NT

    Hey! Apologies for pinging a two-month-old thread, but I do find this important, and, as always, there aren't many sources of information on this kind of topic.

    So, why exactly was the demonstration of the optimal usage of stackalloc removed from the page, when it had previously been explicitly added in? Running the tests using the latest version of the .NET 10 runtime, it's still very clear that allocating a buffer of constant length on the stack is much more preferable to allocating one of variable length, as it can be 2 to 3 times faster (especially when users don't opt out of having the said buffer zeroed out), while also producing slimmer code byte-wise.

    Are there any optimizations regarding this scenario scheduled for .NET 11's JIT? Is there a thread about them somewhere that I could read up on? If so, I'd still recommend mentioning the obsolescence of an old best practice that people have been following all this time, in order to inform the community about this change.

    Otherwise, if this change was made without much thought put into it, I'd strongly recommend reverting the article to its previous state. Or, better yet, swapping the line with:

    Span<byte> buffer = (uint)inputLength <= MaxStackLimit ? (stackalloc byte[MaxStackLimit])[..inputLength] : new byte[inputLength];
    

    since it more closely aligns with real-life scenarios, where developers usually need a buffer of a specific length for their task, and this variant also often has a chance of doing even less work than the original inputLength <= MaxStackLimit ? stackalloc byte[MaxStackLimit] : new byte[inputLength].


    Also, as a treat for any interested souls who might stumble upon this thread, here are the benchmark results for a maximum buffer size of 256:

    Method length Mean Error StdDev Ratio RatioSD Code Size
    VarLength 200 6.492 ns 0.0899 ns 0.0797 ns 1.00 0.02 110 B
    ConstLength 200 2.418 ns 0.0242 ns 0.0215 ns 0.37 0.01 159 B
    ConstLength_Slice 200 2.338 ns 0.0212 ns 0.0177 ns 0.36 0.01 151 B
    Unconditional 200 3.001 ns 0.0358 ns 0.0299 ns 0.46 0.01 158 B
    Unconditional_Slice 200 3.656 ns 0.0282 ns 0.0250 ns 0.56 0.01 185 B
     
    VarLength_NoInit 200 2.414 ns 0.0179 ns 0.0167 ns 1.00 0.01 132 B
    ConstLength_NoInit 200 1.917 ns 0.0241 ns 0.0201 ns 0.79 0.01 101 B
    ConstLength_Slice_NoInit 200 1.836 ns 0.0334 ns 0.0312 ns 0.76 0.01 96 B
    Unconditional_NoInit 200 2.794 ns 0.0528 ns 0.0412 ns 1.16 0.02 103 B
    Unconditional_Slice_NoInit 200 2.041 ns 0.0432 ns 0.0337 ns 0.85 0.01 127 B
     
    VarLength 400 27.724 ns 0.5839 ns 0.6247 ns 1.00 0.03 110 B
    ConstLength 400 27.367 ns 0.1385 ns 0.1228 ns 0.99 0.02 156 B
    ConstLength_Slice 400 28.123 ns 0.4007 ns 0.3748 ns 1.01 0.03 151 B
    Unconditional 400 28.504 ns 0.2552 ns 0.2387 ns 1.03 0.02 156 B
    Unconditional_Slice 400 29.268 ns 0.2054 ns 0.1603 ns 1.06 0.02 183 B
     
    VarLength_NoInit 400 28.099 ns 0.4259 ns 0.3984 ns 1.00 0.02 132 B
    ConstLength_NoInit 400 27.099 ns 0.0510 ns 0.0398 ns 0.96 0.01 101 B
    ConstLength_Slice_NoInit 400 28.118 ns 0.5539 ns 0.4910 ns 1.00 0.02 96 B
    Unconditional_NoInit 400 28.350 ns 0.3821 ns 0.3387 ns 1.01 0.02 101 B
    Unconditional_Slice_NoInit 400 28.273 ns 0.3404 ns 0.2842 ns 1.01 0.02 125 B

    Here are the results for larger buffers with a size of 1024:

    Method length Mean Error StdDev Ratio RatioSD Code Size
    VarLength 1000 33.983 ns 0.1117 ns 0.1045 ns 1.00 0.00 110 B
    ConstLength 1000 15.147 ns 0.0563 ns 0.0500 ns 0.45 0.00 357 B
    ConstLength_Slice 1000 11.138 ns 0.0499 ns 0.0417 ns 0.33 0.00 362 B
    Unconditional 1000 12.853 ns 0.1407 ns 0.1247 ns 0.38 0.00 361 B
    Unconditional_Slice 1000 13.402 ns 0.2661 ns 0.2489 ns 0.39 0.01 383 B
     
    VarLength_NoInit 1000 2.414 ns 0.0216 ns 0.0192 ns 1.00 0.01 132 B
    ConstLength_NoInit 1000 1.897 ns 0.0416 ns 0.0389 ns 0.79 0.02 101 B
    ConstLength_Slice_NoInit 1000 1.804 ns 0.0266 ns 0.0249 ns 0.75 0.01 96 B
    Unconditional_NoInit 1000 1.866 ns 0.0311 ns 0.0260 ns 0.77 0.01 103 B
    Unconditional_Slice_NoInit 1000 1.992 ns 0.0234 ns 0.0183 ns 0.83 0.01 127 B
     
    VarLength 2000 107.392 ns 1.2777 ns 1.1327 ns 1.00 0.01 110 B
    ConstLength 2000 106.864 ns 1.3792 ns 1.2901 ns 1.00 0.02 366 B
    ConstLength_Slice 2000 106.238 ns 0.4296 ns 0.3808 ns 0.99 0.01 367 B
    Unconditional 2000 121.281 ns 1.8240 ns 1.7062 ns 1.13 0.02 359 B
    Unconditional_Slice 2000 118.247 ns 0.9383 ns 0.7836 ns 1.10 0.01 385 B
     
    VarLength_NoInit 2000 105.447 ns 0.5373 ns 0.5026 ns 1.00 0.01 132 B
    ConstLength_NoInit 2000 105.426 ns 0.6352 ns 0.5941 ns 1.00 0.01 101 B
    ConstLength_Slice_NoInit 2000 105.299 ns 0.3936 ns 0.3682 ns 1.00 0.01 96 B
    Unconditional_NoInit 2000 106.162 ns 1.5454 ns 1.4455 ns 1.01 0.01 101 B
    Unconditional_Slice_NoInit 2000 106.783 ns 1.7471 ns 1.4589 ns 1.01 0.01 125 B

    And here are the benchmarks themselves:

    using System.Runtime.CompilerServices;
    using BenchmarkDotNet.Attributes;
    using BenchmarkDotNet.Configs;
    using BenchmarkDotNet.Running;
    
    BenchmarkRunner.Run<Benchmarks>();
    
    [DisassemblyDiagnoser]
    [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory, BenchmarkLogicalGroupRule.ByParams)]
    public class Benchmarks
    {
        public const int MaxLength = 256;
        // public const int MaxLength = 1024;
    
        public IEnumerable<object[]> Length => [[MaxLength / 100 * 100], [MaxLength / 100 * 200]];
    
        [Benchmark(Baseline = true), BenchmarkCategory("LocalsInit"), ArgumentsSource(nameof(Length))]
        public void VarLength(int length)
        {
            Span<byte> span = (uint)length <= MaxLength ? stackalloc byte[length] : new byte[length];
            Consume(span);
        }
    
        [Benchmark, BenchmarkCategory("LocalsInit"), ArgumentsSource(nameof(Length))]
        public void ConstLength(int length)
        {
            Span<byte> span = (uint)length <= MaxLength ? stackalloc byte[MaxLength] : new byte[length];
            Consume(span);
        }
    
        [Benchmark, BenchmarkCategory("LocalsInit"), ArgumentsSource(nameof(Length))]
        public void ConstLength_Slice(int length)
        {
            Span<byte> span = (uint)length <= MaxLength ? (stackalloc byte[MaxLength])[..length] : new byte[length];
            Consume(span);
        }
    
        [Benchmark, BenchmarkCategory("LocalsInit"), ArgumentsSource(nameof(Length))]
        public void Unconditional(int length)
        {
            Span<byte> span = stackalloc byte[MaxLength];
            if ((uint)length > MaxLength)
                span = new byte[length];
    
            Consume(span);
        }
    
        [Benchmark, BenchmarkCategory("LocalsInit"), ArgumentsSource(nameof(Length))]
        public void Unconditional_Slice(int length)
        {
            Span<byte> span = stackalloc byte[MaxLength];
            if ((uint)length > MaxLength)
                span = new byte[length];
    
            span = span[..length];
            Consume(span);
        }
    
        [Benchmark(Baseline = true), BenchmarkCategory("SkipLocalsInit"), ArgumentsSource(nameof(Length))]
        [SkipLocalsInit]
        public void VarLength_NoInit(int length)
        {
            Span<byte> span = (uint)length <= MaxLength ? stackalloc byte[length] : new byte[length];
            Consume(span);
        }
    
        [Benchmark, BenchmarkCategory("SkipLocalsInit"), ArgumentsSource(nameof(Length))]
        [SkipLocalsInit]
        public void ConstLength_NoInit(int length)
        {
            Span<byte> span = (uint)length <= MaxLength ? stackalloc byte[MaxLength] : new byte[length];
            Consume(span);
        }
    
        [Benchmark, BenchmarkCategory("SkipLocalsInit"), ArgumentsSource(nameof(Length))]
        [SkipLocalsInit]
        public void ConstLength_Slice_NoInit(int length)
        {
            Span<byte> span = (uint)length <= MaxLength ? (stackalloc byte[MaxLength])[..length] : new byte[length];
            Consume(span);
        }
    
        [Benchmark, BenchmarkCategory("SkipLocalsInit"), ArgumentsSource(nameof(Length))]
        [SkipLocalsInit]
        public void Unconditional_NoInit(int length)
        {
            Span<byte> span = stackalloc byte[MaxLength];
            if ((uint)length > MaxLength)
                span = new byte[length];
    
            Consume(span);
        }
    
        [Benchmark, BenchmarkCategory("SkipLocalsInit"), ArgumentsSource(nameof(Length))]
        [SkipLocalsInit]
        public void Unconditional_Slice_NoInit(int length)
        {
            Span<byte> span = stackalloc byte[MaxLength];
            if ((uint)length > MaxLength)
                span = new byte[length];
    
            span = span[..length];
            Consume(span);
        }
    
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void Consume(Span<byte> _) { }
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions