This product is not supported for your selected Datadog site. ().

Metadata

ID: csharp-best-practices/loop-stackalloc

Language: C#

Severity: Warning

Category: Performance

Description

This rule warns against using stackalloc inside loops. Allocating memory on the stack in each iteration can lead to excessive stack usage, which may cause stack overflow exceptions and degrade application performance. To avoid this issue, allocate the stack memory once outside the loop and reuse it within the loop body.

Non-Compliant Code Examples

for (int i = 0; i < 10; i++)
{
    Span<byte> buffer = stackalloc byte[256];
    buffer.Clear();
}

Compliant Code Examples

Span<byte> buffer = stackalloc byte[256];
for (int i = 0; i < 10; i++)
{
    buffer.Clear();
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security