3 ms·
The main use cases are actually way more mundane, but also much more impactful. Consider some of the most common string manipulation code you see: grab a substr
by Locke1689 10y ago
The main use cases are actually way more mundane, but also much more impactful. Consider some of the most common string manipulation code you see: grab a substring, compare it to some stuff, branch based on results.
Since strings are immutable and non-sharing, all substring calls will create copies of the substring. With Span<T>, you could instead simply request a span of the string and, with unification in the underlying typing, you can perform all of your string manipulation with no allocations or copying.
- nanch 10y agoI'm all aboard the existing use cases for Span<T>. I said that when I said "interesting value add inclusion." for the Span<T> inclusion. Not sure I get your comment.
- Locke1689 10y agoOh, just clarifying for people that it's not just unusual apps with large blocks of memory that will benefit. Even mundane apps that do a little string manipulation will see the results.
- voltagex_ 10y agoI wonder how much string manipulation you'd have to be doing to see a benefit. I still can't use C#6 everywhere at work because some teams insist on being in VS2010 / 2012, so I'd be pretty worried about going to C#7.
- ygra 10y agoA lot, I guess. Famously, Java's String worked that way (sharing the buffer for sub-strings and only storing offset and length) for a long time, until they changed that, I think in Java 7 to the same what .NET uses currently (copying the sub-string). Both approaches have benefits and drawbacks, but apparently copying the sub-string seems to be best for the vast majority of cases and you only benefit from the shared buffer in select cases (also it's a great memory leak opportunity if you don't know how it's implemented). So I guess it makes sense for .NET to add the capability (in a more general form that also works for other things) instead of only having one or the other.
- Locke1689 10y agoThe problem with sharing is that you can inadvertently keep a massive string alive by only holding on to a tiny piece of it. Span<T> conveniently side steps this issue by only existing on the stack, meaning that you can't stash away the span somewhere and accidentally keep the underlying buffer alive longer than necessary.