All rules
CA1863Performance Enabled by default: No

Use CompositeFormat

Use CompositeFormat

Microsoft docs

Description

It's expensive to parse a format string at runtime. This rule locates places in your code where you can cache and use a System.Text.CompositeFormat instance as the argument to a formatting operation, rather than passing in the original format string. A System.Text.CompositeFormat instance parses the composite format string when it's created, which means the "hot path" of string formatting can execute much faster.

Cause

Code calls System.String.Format(System.String,System.Object[]) or System.Text.StringBuilder.AppendFormat(System.String,System.Object[]) with a static format string that hasn't been cached to a System.Text.CompositeFormat instance.

How to fix violations

Create an instance of System.Text.CompositeFormat by calling System.Text.CompositeFormat.Parse(System.String) and pass it to System.String.Format(System.IFormatProvider,System.Text.CompositeFormat,System.Object[]) or System.Text.StringBuilder.AppendFormat(System.IFormatProvider,System.Text.CompositeFormat,System.Object[]) instead of the original format string.

Example

class C
{
    private static readonly string StaticField = "Format one value: {0}";

    static void Main()
    {
        _ = string.Format(StaticField, 42);

        StringBuilder sb = new();
        sb.AppendFormat(StaticField, 42);
    }
}

class C
{
    private static readonly CompositeFormat StaticField = CompositeFormat.Parse("Format one value: {0}");

    static void Main()
    {
        _ = string.Format(null, StaticField, 42);

        StringBuilder sb = new();
        sb.AppendFormat(null, StaticField, 42);
    }
}

When to suppress

It's safe to suppress diagnostics from this rule if performance isn't a concern.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0