Big Data

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.Split() and String.Split() methods using BenchmarkDotNet. 

IDG

As you can see from the benchmarking results in Figure 2, the ReadOnlySpan.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.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.



READ SOURCE

This website uses cookies. By continuing to use this site, you accept our use of cookies.