The article demonstrates the importance of using StringComparison options for efficient string comparison in .NET
Whether it's searching, sorting, or equality, how you compare strings can significantly impact your application performance. The article demonstrates the importance of using StringComparison options for efficient string comparison in .NET
Consider the following common approach used by most developers for string comparison:
// Inefficient string comparison
bool equal = string1.ToLower() == string2.ToLower();
.NET provides a powerful enumeration, StringComparison, designed to address these inefficiencies.
// Efficient string comparison
bool equal = string.Equals(string1, string2, StringComparison.OrdinalIgnoreCase);
The aforementioned addresses both of the problems in the old string comparison way.
Create another class named StringComparisons and add the following code snippet
public static class StringComparisons
{
private static readonly string string1 = "test";
private static readonly string string2 = "test";
public static void BadMethod()
{
// Inefficient string comparison
bool equal = string1.ToLower() == string2.ToLower();
Console.WriteLine($"In bad method strings are {equal}");
}
public static void GoodMethod()
{
// efficient string comparison
bool equal = string.Equals(string1, string2, System.StringComparison.OrdinalIgnoreCase);
Console.WriteLine($"In good method strings are {equal}");
}
}
Execute from the main method as follows
#region Day 21: String Comparisons
static string ExecuteDay21()
{
StringComparisons.BadMethod();
StringComparisons.GoodMethod();
return "Executed Day 21 successfully..!!";
}
#endregion
Console output
In bad method strings are True
In good method strings are True
GitHub — ssukhpinder/30DayChallenge.Net
Thank you for being a part of the C# community! Before you leave:
Follow us: Youtube | X | LinkedIn | Dev.to Visit our other platforms: GitHub More content at C# Programming