-
Notifications
You must be signed in to change notification settings - Fork 485
Description
Using ReadOnlyMemory<byte>
or ReadOnlySpan<byte>
can offer several advantages over byte[]
in certain scenarios:
-
Immutability:
ReadOnlyMemory<byte>
andReadOnlySpan<byte>
provide a way to represent read-only data. This ensures that the underlying data cannot be modified, which can help prevent bugs and improve code safety. -
Performance:
ReadOnlySpan<byte>
is a stack-only type, which means it can be used without heap allocations. This can lead to performance improvements, especially in high-performance or low-latency applications. -
Memory Efficiency:
ReadOnlyMemory<byte>
andReadOnlySpan<byte>
can represent a segment of an array without copying the data. This can save memory and reduce the overhead associated with creating new arrays. -
Flexibility: These types can be used to represent data from various sources, such as arrays, strings, or even unmanaged memory. This makes them more versatile compared to
byte[]
. -
Safety: By using read-only types, you can enforce the principle of least privilege, ensuring that methods only have access to the data they need without the ability to modify it.
This would also allow to get intermediate byte arrays from ArrayPool<byte>.Shared
instead of allocating new byte[]
all the time.
At least, consider using ArraySegment<byte>
.