String.Split VS. Regex.Split?

Viewed 25936

If I have a delimited text file with a basic delimiter (say | for instance) does it make a difference whether I use a String or a Regex split?

Would I see any performance gains with one versus the other?

I am assuming you would want to use Regex.Split if you have escaped delimiters that you don't want to split on (\| for example).

Are there any other reasons to use Regex.Split vs String.Split?

4 Answers

It seems that for simple scenarios string.Split() would work much better. I ran a test in Benchmark .NET

Tested on .NetCore 2.2.6:


Method Mean Error StdDev Median
RegexSplit 486.47 ns 9.769 ns 24.15 ns 481.72 ns
Split 84.76 ns 4.503 ns 13.21 ns 81.12 ns

Tested on .Net 5.0.101:


Method Mean Error StdDev
RegexSplit 182.10 ns 2.091 ns 1.956 ns
Split 50.29 ns 0.709 ns 0.663 ns

note: not run on the same hardware, so the relative differences in performance between dotnet versions is more important than the absolute differences.

The Test:

public class RegexVsSplit
{
    private readonly string data = "host:7000";

    public RegexVsSplit()
    {
    }

    [Benchmark]
    public string[] RegexSplit() => Regex.Split(data, ":");

    [Benchmark]
    public string[] Split() => data.Split(':');
}
Related