Last active
May 26, 2022 19:36
-
-
Save zett42/775a6662dace92237acc824c07b37e93 to your computer and use it in GitHub Desktop.
Benchmark methods for getting index of first non-whitespace character in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using BenchmarkDotNet.Running; | |
using BenchmarkDotNet.Attributes; | |
using System.Text.RegularExpressions; | |
namespace Benchmark_IndexOfFirstNonWhitespaceChar { | |
class Program { | |
static void Main( string[] args ) { | |
var summary = BenchmarkRunner.Run<Test>(); | |
} | |
} | |
public class Test { | |
string text = new string(' ', 50000 ) + new string('x', 50000 ); | |
Regex regex = new Regex( @"\S" ); | |
Regex regexCompiled = new Regex( @"\S", RegexOptions.Compiled ); | |
[Benchmark] | |
public int Linq_TakeWhile() { | |
return text.TakeWhile( char.IsWhiteSpace ).Count(); | |
} | |
[Benchmark] | |
public int String_Trim() { | |
return text.Length - text.TrimStart().Length; | |
} | |
[Benchmark] | |
public int ReadOnlySpan_Trim() { | |
return text.Length - text.AsSpan().TrimStart().Length; | |
} | |
[Benchmark] | |
public int StringExt_IndexOfPredicate() { | |
return text.IndexOf<char>( c => !char.IsWhiteSpace( c ) ); | |
} | |
[Benchmark] | |
public int Array_FindIndex() { | |
return Array.FindIndex( text.ToCharArray(), x => !char.IsWhiteSpace( x ) ); | |
} | |
[Benchmark] | |
public int Regex_Interpreted() { | |
return regex.Match( text ).Index; | |
} | |
[Benchmark] | |
public int Regex_Compiled() { | |
return regexCompiled.Match( text ).Index; | |
} | |
[Benchmark] | |
public int Regex_StaticMethod() { | |
return Regex.Match( text, @"\S" ).Index; | |
} | |
[Benchmark] | |
public int FirstNonMatch() { | |
return _FirstNonMatch( text, char.IsWhiteSpace); | |
} | |
private static int _FirstNonMatch(string s, Func<char, bool> predicate, int startPosition = 0) | |
{ | |
for (var i = startPosition; i < s.Length; i++) | |
if (!predicate(s[i])) return i; | |
return -1; | |
} | |
} | |
public static class MyStringExtensions { | |
public static int IndexOf<TSource>(this IEnumerable<TSource> source, | |
Func<TSource, bool> predicate) | |
{ | |
int i = 0; | |
foreach (TSource element in source) | |
{ | |
if (predicate(element)) | |
return i; | |
i++; | |
} | |
return -1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment