CompositeFormat: Stop Re-Parsing Format Strings on Every Call

string.Format("{0} processed {1} items in {2:F2}ms", name, count, elapsed) looks innocent enough. But every time you call it, the runtime parses that format string from scratch — finding the {0}, {1:F2} placeholders, validating them, and building the output. Call it once? Fine. Call it 100,000 times in a logging or reporting hot path? That parsing adds up.

CompositeFormat lets you parse the format string once and reuse the compiled representation forever.

The Before

// In a high-throughput logger or report generator
for (int i = 0; i < records.Length; i++)
{
// Parses the format string on EVERY iteration
var line = string.Format(
"[{0:yyyy-MM-dd HH:mm:ss}] {1}: processed {2:N0} records ({3:P1} complete)",
records[i].Timestamp,
records[i].Name,
records[i].Count,
records[i].Progress);
output.AppendLine(line);
}

The After

using System.Text;
// Parse once at startup
private static readonly CompositeFormat LogFormat = CompositeFormat.Parse(
"[{0:yyyy-MM-dd HH:mm:ss}] {1}: processed {2:N0} records ({3:P1} complete)");
// Use the pre-parsed format in the hot path
for (int i = 0; i < records.Length; i++)
{
var line = string.Format(
null, // IFormatProvider (null = current culture)
LogFormat, // pre-parsed, no re-parsing
records[i].Timestamp,
records[i].Name,
records[i].Count,
records[i].Progress);
output.AppendLine(line);
}

The CompositeFormat.Parse() call does the format string analysis once. Every subsequent string.Format call with that CompositeFormat skips the parsing step entirely and goes straight to writing output.

Works with StringBuilder Too

private static readonly CompositeFormat RowFormat =
CompositeFormat.Parse("| {0,-20} | {1,10:C2} | {2,8:N0} |");
var sb = new StringBuilder();
sb.AppendLine("| Product | Price | Quantity |");
sb.AppendLine("|----------------------|------------|----------|");
foreach (var item in inventory)
{
sb.AppendFormat(null, RowFormat, item.Name, item.Price, item.Quantity);
sb.AppendLine();
}

When to Use It

  • Logging pipelines where the same format pattern is applied to millions of entries
  • Report generators that format table rows, CSV lines, or export records
  • Template engines that apply the same pattern repeatedly with different data
  • Any loop where string.Format with a constant format string shows up in your profiler

When NOT to Use It

If your format string is used once or rarely, the overhead of pre-parsing isn’t worth it. CompositeFormat shines specifically in high-repetition scenarios.

Key Takeaway

CompositeFormat.Parse() compiles your format string once. Every subsequent string.Format(provider, compositeFormat, args) call skips re-parsing and goes straight to output. It’s a one-line change that eliminates redundant string parsing on hot paths. If your profiler highlights string.Format, this is your fix.