Repository navigation
Description
It's extremely common to split a string based on a single char or string separator, yet String.Split only offers overloads that accept an array of separators. The params char[] separator overload is particularly insidious as the params usage often results in a large number of unnecessary char[] heap allocations, unbeknownst to the developer.
Rationale and Usage
Stack Exchange ran into this (significant number of separator arrays in memory) and submitted a pull request to ASP.NET MVC to cache String.Split separator arrays inside the ASP.NET MVC codebase.
They ended up with the following:
namespace System.Web.Mvc
{
internal static class StringSplits
{
// note array contents not technically read-only; just... don't edit them!
internal static readonly char[]
Period = new[] { '.' },
Comma = new[] { ',' };
}
}With uses of string.Split('.') and string.Split(',') replaced with string.Split(StringSplits.Period) and string.Split(StringSplits.Comma) to avoid the char[] allocations.
It'd be awesome if String.Split offered overloads that accepted a single separator to avoid this.
Proposed API
public partial class String
{
// Proposed methods
public string[] Split(char separator, StringSplitOptions options = StringSplitOptions.None);
public string[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None);
public string[] Split(string separator, StringSplitOptions options = StringSplitOptions.None);
public string[] Split(string separator, int count, StringSplitOptions options = StringSplitOptions.None);
// Existing methods
public string[] Split(params char[] separator);
public string[] Split(char[] separator, int count);
public string[] Split(char[] separator, StringSplitOptions options);
public string[] Split(char[] separator, int count, StringSplitOptions options);
public string[] Split(string[] separator, StringSplitOptions options);
public string[] Split(string[] separator, int count, StringSplitOptions options);
}Notes
We had wanted to add public string[] Split(string separator), but this breaks source compatibility with uses of Split(null), which is documented to split based on white space, because it makes the call ambiguous between Split(char[]) and Split(string).
I won't go into it here as it's really a separate feature request, but it would also be worth considering new Split methods that return a struct collection of StringSpan/StringSegment structs (in lieu of internal runtime span/substring magic) to avoid the resulting string[] allocation (and substring allocations, unless needed).
I'd be happy to contribute an implementation and tests.
Activity
ellismg commentedon Apr 25, 2015
Please open an issue on this. We have been talking about it from time to time internally (and I've done a fair amount of thinking and prototyping) but we should open the discussion up. There are lots of interesting issues to consider.
ellismg commentedon Apr 25, 2015
I think this would be a great addition to the framework.
svick commentedon Apr 25, 2015
Depending on if and how slices are implemented, that
StringSpanversion might not be necessary, I think.weshaggard commentedon Apr 25, 2015
@justinvp I think these are some reasonable asks and I think the discussion should happen here in the corefx repo regardless of whether we end up putting these directly on string in the coreclr repo or not.
I also like the other idea of a generally more efficient string split that uses structs and agree that it should be a separate issue but it is worth mentioning here and considering it along with these to have a more holistic look at our different split options.
One question I wonder about this is do you have any numbers that show how much of an improvement something like this might have? Knowing that split is really bad about allocations is the actual params array really going to show as much of an improvement in the overall amount of allocations that occur or will it just be a tiny improvement and switching to the struct split is ultimately what people should do to get the performance they need. In other words is the params array 1 of 20 allocations or 1 of 2 allocations in this code. I suspect it depends on the number of items that end up in the split string array but it is worth thinking about.
mattwarren commentedon Apr 25, 2015
+1 👍 from me.
I like the general trend I see in a lot of the new work in .NET. There seems to be a concerted effort to ensure there are as few allocations as possible (i.e. stuff like this https://github.com/dotnet/corefxlab/wiki)
pharring commentedon Apr 27, 2015
string.Split is an awful allocation hog and I've learned to avoid it. Not only the params char[] args and the obvious returned array, but the implementation allocates an int[] for all the split locations.
Often, string.Split is unnecessary. Iteration with string.IndexOf is allocation free and, if you really need substrings, well those allocations are unavoidable.
I think an alternative API which returns a struct-based enumerator of spans would be ideal - similar to the note in the proposal. It would encourage people to think more of "parsing" and less about "splitting".
krwq commentedon Apr 28, 2015
While I agree on a single character overload, the string overload is not obvious to me. I.e.: What is the expected result of "aaabaaabaaa".Split("aa")? ["", "ab", "ab", "a"] or rather ["a", "b", "ab", "a"]? Or should this string be treated as char[] overload and work the same as that?
mgravell commentedon Apr 28, 2015
What @pharring says here makes a lot of sense - especially with the immutability of strings making it trivially repeatable; a custom struct iterator would be virtually free (until, of course, someone uses LINQ on it, causing it to box - but hey; we can't have everything).
pharring commentedon Apr 28, 2015
@krwq the matching rules for the string overload would be the same as they are today with the char[] version. The string is just an alternative way of packaging the set of separator chars. Repeated chars are ignored.
krwq commentedon Apr 28, 2015
@pharring, in this case I don't think this API is a good idea. In my opinion it is gonna be confusing with splitting a string by separator which is string. I'd rather have slow API which intentions are clear. Can we expose some non allocating API which gives you ImmutableArray from string which will have a char[] underneath which we can consume without new allocations? Besides we usually call Split quite rarely so what's the point on saving few nanoseconds/bytes per instance?
davkean commentedon Apr 28, 2015
@krwq I don't understand your concern, this proposal does not add any new features to String.Split. As @pharring mentioned, this is just a way to avoid the initial allocation of passing the separators to String.Split.
Introducing a new non-allocating String.Split is a great idea that we've talked about a lot in the past, however, it should be treated separably to this proposal and not as an "either or".
ellismg commentedon Apr 28, 2015
@pharring @krwq I would assume the string versions would just be aliases for the string[] versions. In this case:
behaves the same way as
So you would get:
eatdrinksleepcode commentedon Apr 28, 2015
I think what @krwq is saying is that if the method call is "Split(String separator)", it is not clear whether the separator is a single multi-character separator or a collection of single-character separators expressed as a string.
I agree that this would be confusing and would prefer that it not be included. Despite the fact that String implements IEnumerable, I can't think of another API that treats a string as a collection of characters in this way.
ellismg commentedon Apr 28, 2015
I would have expected that most folks would assume that
is going to give you back
and not
I could maybe buy the argument if we didn't have any existing overloads of Split that took strings, but we already have clear semantics for how to split using one or more strings as a splitter.
eatdrinksleepcode commentedon Apr 28, 2015
@ellismg I agree with your interpretation, but @pharring's explanation seems to indicate otherwise.
19 remaining items
justinvp commentedon Aug 25, 2016
@svick interesting idea. Does it work in VB? F#? (Are there any other CLR languages we care about?)
svick commentedon Aug 25, 2016
@justinvp Based on a quick test, it does seem to work in VB and F#.
Interestingly, VB does not report ambiguity error (and chooses the
char[]overload) even with the original code (i.e. without the optional parameter), not sure why (haven't checked the spec).justinvp commentedon Sep 8, 2016
@weshaggard, @terrajobst,
Should we go with @svick's optional parameter idea? If yes, that leaves us with:
A) For consistency between
stringandchar, should we make thecharoverload use an optional parameter as well? e.g.:B) If yes to A, should we also make
optionsoptional in the overloads with thecountparameter? e.g.:C) If yes to B, should we make
countoptional and collapse the overloads? e.g.:Personally, I think C goes a bit too far with the optionals. I prefer B because B more closely aligns with the existing
Splitmethods where you can callSplit(sep, options)without having to specify theoptionsparam name (e.g.Split(sep, options: options)), which is what you'd have to do if we went with C.Here's what B looks like with the existing methods:
B+) Which begs the question... Would it be possible to modify the existing
string[]methods to makeoptionsoptional? It'd be a compatible change, right? e.g.:B+ would make calling
Splitconsistent across the board. You'd be able to callSplit(new string[] { "1", "2" })without having to specifyoptions, just like you can already callSplit(new char[] { '1', '2' })without having to specifyoptions, and just like how you'll be able to call the newSplit("1")andSplit('1')methods without having to specifyoptions. The same goes for callingSplitwithcountwithout having to specifyoptions.weshaggard commentedon Sep 8, 2016
That is a lot of options to consider. I marked this as api-ready-for-review so it will show up in our triage query again and we will review at our next review meeting (usually every Tuesday morning).
terrajobst commentedon Sep 13, 2016
We've decided to go with option B. Technically, that means calls like this:
are still ambiguous, but we accept that because that's already the case for the API shape as it was shipped.
justinvp commentedon Sep 13, 2016
Thanks, Immo. CoreCLR PR here: dotnet/coreclr#7175
karelz commentedon Oct 9, 2016
What's remaining to close it?
justinvp commentedon Oct 9, 2016
Hi Karel! Long time no see 😃. I opened dotnet/corefx#12495 to expose these in netcoreapp1.1. Once that's merged, I think we can close this, assuming it doesn't need to stay open to track adding to the desktop framework and mono.
karelz commentedon Oct 10, 2016
Hey Justin, good to see you here :).
Thanks for your changes. We can close it with your PR. Porting to other platforms will be taken care of by the netfx-port-consider tag.