Skip to content

Conversation

epeshk
Copy link
Contributor

@epeshk epeshk commented Jul 25, 2024

This PR removes allocations from legacy (but still not deprecated in Console/File sinks) MessageTemplateTextFormatter. This may still be useful, since the timestamp is serialized for each log event.

Allocations:

  • DateTimeOffset boxing, by adding ScalarValue.Render<T> overload with constraint for IFormattable
  • DateTimeOffset.ToString() allocation, by using ISpanFormattable.TryFormat API

OutputTemplateRenderingBenchmark.FormatToOutput

Before

Method Job Runtime Mean Error StdDev Gen0 Allocated
FormatToOutput .NET 8.0 .NET 8.0 184.9 ns 1.93 ns 1.81 ns 0.0143 120 B
FormatToOutput .NET 9.0 .NET 9.0 141.3 ns 1.50 ns 1.40 ns 0.0143 120 B

After

Method Job Runtime Mean Error StdDev Allocated
FormatToOutput .NET 8.0 .NET 8.0 190.2 ns 1.70 ns 1.59 ns -
FormatToOutput .NET 9.0 .NET 9.0 135.6 ns 1.02 ns 0.95 ns -

…alization for legacy (but still frequently used) MessageTemplateTextFormatter
@nblumhardt
Copy link
Member

Looks like a great change, left a comment on the other version of this PR which I think will also apply here: serilog/serilog-expressions#121

Cheers!

epeshk added 2 commits August 5, 2024 21:57
…hods

Original StringWriter.Write/WriteLine(ReadOnlySpan<char>) methods are optimized only for the StringWriter type itself, not derived classes. For derived classes, these methods copy the provided Span to an array from ArrayPool and fall back to Write(char[], int, int) method for backward compatibility with code created before the Span type existed.

Explicit overrides in the ReusableStringWriter class that call StringBuilder.Append directly help to avoid the overhead of ArrayPool.Rent/Return and copying.
@nblumhardt nblumhardt merged commit 3f6d855 into serilog:dev Aug 20, 2024
1 check passed
@nblumhardt
Copy link
Member

Thanks Evgeny! 👍

@nblumhardt nblumhardt mentioned this pull request Sep 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants