C# Char in String Equals ValueBenchmark a fast way to test char values. See if a char in a string equals a value.
dot net perls
Char test. Consider a string. We can test it with complex methods with StartsWith or EndsWith. Or we can test individual strings, giving our logic more flexibility.
Specialized logic. We can also arrange if-tests with chars to avoid repeated work—for example, if we want to test multiple strings starting with a letter, we can test that value once.
A simple example. Here is a simple example of testing the first letter in a string. Here we see if the string equals the lowercase letter "t."
StartsWith, EndsWith
C# program that uses char test
using System; class Program { static void Main() { string value = "test"; // See if first char is the lowercase T. if (value[0] == 't') { Console.WriteLine("First char is t"); } } }
First char is t
Benchmark, char testing. Suppose we need to test a string thousands to billions of times. We benchmark an alternative way of comparing constant strings.
Version 1 This version of the code uses the EndsWith method, and tests the end of a string.
Version 2 This code uses individual char testing in an if-statement, and it has the same result as version 1.
Result In 2021 (with .NET 5 on Linux) it is faster to simply call EndsWith instead of individual char testing.
C# program that benchmarks EndsWith, char testing
using System; using System.Diagnostics; class Program { static bool EndsThreeA(string s) { return s.EndsWith("three", StringComparison.Ordinal); } static bool EndsThreeB(string s) { int len = s.Length; if (len >= 5 && s[len - 5] == 't' && s[len - 4] == 'h' && s[len - 3] == 'r' && s[len - 2] == 'e' && s[len - 1] == 'e') { return true; } else { return false; } } const int _max = 1000000; static void Main() { var s1 = Stopwatch.StartNew(); // Version 1: use EndsWith. for (int i = 0; i < _max; i++) { if (!EndsThreeA("test three")) { return; } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: use char-testing method. for (int i = 0; i < _max; i++) { if (!EndsThreeB("test three")) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }
10.53 ns EndsWith 14.16 ns Char testing
A summary. We tested individual chars in C# strings. In recent versions of .NET, we find that StartsWith and EndsWith have been optimized.
© 2007-2021 sam allen. see site info on the changelog