Avoid Unnecessary String Creation

ID

csharp.avoid_unnecessary_string_creation

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

CSharp

Tags

efficiency, performance, string

Description

Reports comparisons against the empty string literal "": both x == "" / x != "" and x.Equals(""). The empty literal is materialised at the comparison site (the JIT may intern it, but the source is still wasteful) and there are clearer alternatives that do not allocate a literal at all.

Rationale

x.Length == 0 does the same check without referencing the empty literal and is unambiguous about the intent (check the length). string.IsNullOrEmpty(x) is preferable when x may be null. Either alternative is at least as fast as the empty-literal compare and reads better.

public class Empty
{
    public bool A(string x) => x == "";                       // FLAW
    public bool B(string x) => "" != x;                       // FLAW
    public bool C(string x) => x.Equals("");                  // FLAW

    public bool D(string x) => x.Length == 0;                 // OK
    public bool E(string x) => string.IsNullOrEmpty(x);       // OK
}

Remediation

Replace x == "" with x.Length == 0 (when x is known non-null) or string.IsNullOrEmpty(x) (when x may be null). Replace x.Equals("") the same way.