Collection Performance: Converting Byte Array to Memory<> and ReadOnlyMemory<>

If you are dealing with byte arrays and require the conversion to Memory<byte>, there are two methods to achieve this, with one being more performant. Here is an example:

Memory<byte> memory = byteArray[0..100];

Here is an example of achieving the same result using AsMemory():

var memory = _byteArray.AsMemory()[0..100];

AsMemory() can also be utilized to convert a byte array to ReadOnlyMemory<> as demonstrated in this example:

ReadOnlyMemory<byte> span = _bytes.AsMemory()[0..Count];

Using AsMemory() is important for several reasons:

  • Performance Optimization: Utilizing AsMemory() directly provides access to a portion of an array without creating temporary copies or new arrays. This eliminates unnecessary memory allocations and potential garbage collection overhead, resulting in significant performance gains. This is especially beneficial in scenarios involving large arrays or frequent array operations.
  • Efficient Memory Management: AsMemory() enables working with segments of arrays without allocating additional memory. This reduces overall memory usage and alleviates pressure on the garbage collector. This aspect is crucial for memory-sensitive applications and those handling large datasets.
  • Improved Code Clarity and Modernity: AsMemory() offers a more concise and expressive way to work with array segments, enhancing code readability and maintainability. Adopting these methods contributes to writing clearer and more modern code.
  • Future-Proofing Code: As the .NET framework evolves, features and APIs are optimized for working with Span and Memory. By incorporating these constructs into your code now, you ensure that it is ready for future .NET versions and potential performance enhancements. This proactive approach helps maintain the efficiency and relevance of your code over time.

Benchmark Results

The benchmark results clearly demonstrate the significant performance advantage of using AsMemory(). With a performance improvement of 57 times compared to other methods, and the additional benefit of not allocating any memory, it underscores the efficiency gains achievable through this approach. This reinforces the importance of choosing AsMemory() for optimal performance, particularly in scenarios where memory allocation and efficient array handling are critical considerations.

Allocations: Range: 40 – 2,072 bytes.

Utilizing AsMemory() to transform a byte array into ReadOnlyMemory<> demonstrates a 57-fold performance improvement, as indicated by the following results.

Allocations: Normal: 40 – 2,072 bytes.

When converting a byte array to Memory<> or ReadOnlyMemory<>, I recommend always using AsMemory().

This is how I have it setup in my EditorConfig to ensure AsMemory() is used: dotnet_diagnostic.CA1833.severity = error

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.