Avoid StartsWith or EndsWith with one character

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: csharp-best-practices/strings-with-one-char

Language: C#

Severity: Warning

Category: Performance

Description

This rule is designed to ensure that you use the most efficient methods for string comparison in C#. When using the StartsWith or EndsWith methods with a single character, the performance can be significantly reduced compared to using the indexer with the first or last index. This is because these methods are designed to work with substrings, not single characters, and therefore involve unnecessary overhead when used in this way.

The importance of this rule lies in writing efficient and performant code. In large-scale applications, using inefficient methods for string comparison can lead to noticeable performance issues. Therefore, it’s crucial to use the appropriate methods for each specific use-case.

Learn More

Non-Compliant Code Examples

using System.Xml;

class MyClass {
    public static void processString(string s)
    {
        bool r1 = s.StartsWith("/");
        bool r2 = s.EndsWith("/");
        data.Contains("\\n");
    }
}

Compliant Code Examples

using System.Xml;

class MyClass {
    public static void processString(string s)
    {
        bool r1 = s.StartsWith('/');
        bool r2 = s.EndsWith('/');
        bool r3 = s.EndsWith("/", StringComparison.InvariantCulture);
        
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis