.NET by Patrik

Building Log Summaries Without Unnecessary Collections

Sometimes data is created only to be logged and never used again. Creating intermediate lists or arrays in those cases increases memory usage and adds unnecessary complexity.

A summary string can often be built directly from the source data:

var summary =
    string.Join(", ",
        source.Select(x => x.Name));

logger.LogInformation("Items=[{Items}]", summary);

If the source might be null, a safe fallback avoids runtime errors:

var safeSource = source ?? Enumerable.Empty<Item>();

var summary =
    string.Join(", ",
        safeSource.Select(x => x.Name));

logger.LogInformation("Items=[{Items}]", summary);

This approach keeps the code lean while still producing clear, useful log output.

logging
performance
strings
efficiency
bestpractice

Comments