4 ms·
Humble request: can anyone explain whether or not Span<T> is interesting if you mostly work with application code (as opposed to, say, low-level or framework co
by nlawalker 8y ago
Humble request: can anyone explain whether or not Span<T> is interesting if you mostly work with application code (as opposed to, say, low-level or framework code) and never work with unmanaged/native code, and why?
From my perspective, it seems like something that'll be used in the guts of ASP.NET and the rest of the base class library that will benefit the performance of my code, but I'd never really use it directly.
- runfaster2000 8y agoCorrect. Most developers will not deal with it much directly, particularly not in the way that it is used in the "guts" of the product.
- yread 8y agoIt can help prevent allocations if you work with large arrays or strings
- benaadams 8y agoIf you take substrings of strings; using string.AsSpan() then allows you to work it as a Span<T> and take windows of the string without allocating an new string for the substrings. Also it means you can now pass readonly arrays (the elements) to things using ReadOnlySpan<T>; so don't have to do defensive copies
- algorithmsRcool 8y agoIf 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.
- zamalek 8y agoSpan (safely refers to data anywhere) and Memory (safely refers to data on the heap only) have a much nicer API than arrays. ArraySegment has had a facelift but to nit: ArraySegment is a pain to type. Also, unlike arrays, there are read-only variants - which are good for rich type checking. In addition you can easily reinterpret cast between blittable types (the new 'unmanaged' generic constraint) for when you are participating in mortal sins such as directly serializing byte representations. Tons of reasons to use them besides performance. We use them for those reasons and if there is a performance boon, great bonus!