4 ms·
If you are at the application level then you can use whatever, but Span<T> is pretty handy. If you are calling an method that has both Span and Array overloads,
by algorithmsRcool 8y ago
If you are at the application level then you can use whatever, but Span<T> is pretty handy. If you are calling an method that has both Span and Array overloads, prefer the Span version since it is less likely to copy or allocate.
The real selling point is that Span is much more flexible than an Array. Both Managed and Unmanged memory can work with it. If you load a big string and need to get each line from it, you can slice into the middle of the string safely and get a ReadOnlySpan<char> that supports most 'string' operations without allocating any memory.
Or imagine you need to process some huge file, typically you would read it chunk by chunk copying the data from the Stream into some byte[]. But with Span you could open a Memory Mapped File and work on segments of the file without copying into temp buffers.
You gain a lot by avoiding memory copies and by allocating fewer objects (less work for the GC). For some workloads then can be a huge speedup.