Skip to content

Consider using ReadOnlyMemory<byte>/ReadOnlySpan<byte> instead of byte[] #1368

@paulomorgado

Description

@paulomorgado

Using ReadOnlyMemory<byte> or ReadOnlySpan<byte> can offer several advantages over byte[] in certain scenarios:

  1. Immutability: ReadOnlyMemory<byte> and ReadOnlySpan<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.

  2. 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.

  3. Memory Efficiency: ReadOnlyMemory<byte> and ReadOnlySpan<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.

  4. 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[].

  5. 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>.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions