Events
Apr 8, 3 PM - May 28, 7 AM
Sharpen your AI skills and enter the sweepstakes to win a free Certification exam
Register now!This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This article describes performance insights for zero-length array allocations.
Allocating zero-length arrays in .NET can lead to unnecessary memory allocations. These allocations, although small, can accumulate and cause performance issues, especially in high-performance or memory-constrained applications.
When a zero-length array is allocated, it results in a memory allocation that's not necessary. Instead of creating a new array, it's more efficient to use the statically allocated empty array instance provided by the Array.Empty<T>()
method. This method returns a cached, empty array of the specified type, avoiding the overhead of a new allocation.
Click the Investigate link to go to the Allocation view showing the allocated zero length array. Double clicking on the allocation shows you the code paths where the allocations are occurring. Consider reducing these allocations using the statically allocated empty array instance provided by Array.Empty<T>()
.
Here is an example of an empty array allocation and its resolution:
Violation:
class Example
{
public void Method()
{
var array = new int[0];
}
}
Resolution:
class Example
{
public void Method()
{
var array = Array.Empty<int>();
}
}
For more information on avoiding zero-length array allocations and other performance best practices, see the following resource:
CA1825: Avoid zero-length array allocations (code analysis)
By following these guidelines, you can ensure that your application is optimized for performance and avoids unnecessary memory overhead.
Events
Apr 8, 3 PM - May 28, 7 AM
Sharpen your AI skills and enter the sweepstakes to win a free Certification exam
Register now!