Skip to main content

Command Palette

Search for a command to run...

Day 21 of 30-Day .NET Challenge: StringComparison

The article demonstrates the importance of using StringComparison options for efficient string comparison in .NET

Published
3 min read
Day 21 of 30-Day .NET Challenge: StringComparison
S

Hi there 👋 I'm Sukhpinder Singh, a passionate self-taught .Net developer from India. Worked on 10+ projects for SQL database design. Developed and maintained over 20 .NET websites with 100% client satisfaction.

Skills C# | Microsoft Certified | Medium Blogger | .Net Core | Xamarin | ASP.Net | Angular


Introduction

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

Learning Objectives

  • The Problem with Inefficient String Comparisons

  • Efficient String Comparison with StringComparison

  • Choosing the Right StringComparison Option

Prerequisites for Developers

  • Basic understanding of C# programming language.

30 Day .Net Challenge
Edit descriptionsinghsukhpinder.medium.com

Getting Started

The Problem with Inefficient String Comparisons

Consider the following common approach used by most developers for string comparison:

// Inefficient string comparison
bool equal = string1.ToLower() == string2.ToLower();
  • The ToLower method creates a new string memory allocation for each comparison, leading to unnecessary allocations. Consider a method with frequent requests that can degrade the application performance.

  • The ToLower method is culture-sensitive, which means it might produce different results depending on the current culture set in the executing thread.

Efficient String Comparison with StringComparison

.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.

  • No Unnecessary Allocations

  • Improved Performance

Choosing the Right StringComparison Option

  • Ordinal: Use for most general-purpose comparisons where cultural rules are not relevant. This is the fastest option.

  • OrdinalIgnoreCase: Ideal for case-insensitive comparisons where cultural rules do not apply.

  • CurrentCulture and CurrentCultureIgnoreCase: Use when comparing strings displayed to the user, where adherence to cultural rules is important.

  • InvariantCulture and InvariantCultureIgnoreCase: Suitable for scenarios requiring consistency across different cultures, such as storing and retrieving data.

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

Complete Code on GitHub

GitHub — ssukhpinder/30DayChallenge.Net
Contribute to ssukhpinder/30DayChallenge.Net development by creating an account on GitHub.github.com


C# Programming🚀

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

30 Day C# Challenge

Part 10 of 30

The series consists of a 30-day code challenge where I'll be diving deep into a different C# concept every single day. 🌟 I'll also be sharing my learnings and insights through engaging articles.

Up next

Day 20 of 30-Day .NET Challenge: Task vs. ValueTask

Heap allocations aren’t entirely bad but when an object is allocated on a heap it contributes to the garbage collection cycles which in turn reduces o