How to split strings efficiently in C#


using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

Finally, to compile the application and execute the benchmarks, run the following command in the console.


dotnet run -p SplitStringsPerformanceBenchmarkDemo.csproj -c Release

Figure 2 shows the results of the executed benchmarks.

split strings c-sharp 02

Figure 2. Comparing the ReadOnlySpan<char>.Split() and String.Split() methods using BenchmarkDotNet. 

IDG

As you can see from the benchmarking results in Figure 2, the ReadOnlySpan<char>.Split() method performs significantly better compared to the String.Split() method. The performance data you see here is only for one run of each of the methods. If you run the benchmark methods multiple times (say, in a loop), you might see even greater performance differences.

The ReadOnlySpan<char>.Split() method is a faster, allocation-free alternative to the String.Split() method in C#. The Span-based methods in C# are much more efficient, requiring hardly any Gen 0 or Gen 1 garbage collections compared to the methods of the String class. They reduce the memory footprint and garbage collection overheads considerably.

About WN

Check Also

News24 | On Christmas Day, Pope Francis calls for talks to end Ukraine war

Pope Francis in his Christmas message on Wednesday called for talks between Ukraine and Russia …

Advertisment ad adsense adlogger