@@ -30,7 +30,7 @@ public SerilogLoggerScope(SerilogLoggerProvider provider, object state, IDisposa
3030 }
3131
3232 public SerilogLoggerScope Parent { get ; }
33-
33+
3434 public void Dispose ( )
3535 {
3636 if ( ! _disposed )
@@ -51,42 +51,57 @@ public void Dispose()
5151
5252 public void EnrichAndCreateScopeItem ( LogEvent logEvent , ILogEventPropertyFactory propertyFactory , out LogEventPropertyValue scopeItem )
5353 {
54+ void AddProperty ( KeyValuePair < string , object > stateProperty )
55+ {
56+ var key = stateProperty . Key ;
57+ var destructureObject = false ;
58+ var value = stateProperty . Value ;
59+
60+ if ( key . StartsWith ( "@" ) )
61+ {
62+ key = key . Substring ( 1 ) ;
63+ destructureObject = true ;
64+ }
65+
66+ if ( key . StartsWith ( "$" ) )
67+ {
68+ key = key . Substring ( 1 ) ;
69+ value = value ? . ToString ( ) ;
70+ }
71+
72+ var property = propertyFactory . CreateProperty ( key , value , destructureObject ) ;
73+ logEvent . AddPropertyIfAbsent ( property ) ;
74+ }
75+
5476 if ( _state == null )
5577 {
5678 scopeItem = null ;
5779 return ;
5880 }
5981
60- if ( _state is IEnumerable < KeyValuePair < string , object > > stateProperties )
82+ // Eliminates boxing of Dictionary<TKey, TValue>.Enumerator for the most common use case
83+ if ( _state is Dictionary < string , object > dictionary )
84+ {
85+ scopeItem = null ; // Unless it's `FormattedLogValues`, these are treated as property bags rather than scope items.
86+
87+ foreach ( var stateProperty in dictionary )
88+ {
89+ if ( stateProperty . Key == SerilogLoggerProvider . OriginalFormatPropertyName && stateProperty . Value is string )
90+ scopeItem = new ScalarValue ( _state . ToString ( ) ) ;
91+ else
92+ AddProperty ( stateProperty ) ;
93+ }
94+ }
95+ else if ( _state is IEnumerable < KeyValuePair < string , object > > stateProperties )
6196 {
6297 scopeItem = null ; // Unless it's `FormattedLogValues`, these are treated as property bags rather than scope items.
6398
6499 foreach ( var stateProperty in stateProperties )
65100 {
66101 if ( stateProperty . Key == SerilogLoggerProvider . OriginalFormatPropertyName && stateProperty . Value is string )
67- {
68102 scopeItem = new ScalarValue ( _state . ToString ( ) ) ;
69- continue ;
70- }
71-
72- var key = stateProperty . Key ;
73- var destructureObject = false ;
74- var value = stateProperty . Value ;
75-
76- if ( key . StartsWith ( "@" ) )
77- {
78- key = key . Substring ( 1 ) ;
79- destructureObject = true ;
80- }
81-
82- if ( key . StartsWith ( "$" ) )
83- {
84- key = key . Substring ( 1 ) ;
85- value = value ? . ToString ( ) ;
86- }
87-
88- var property = propertyFactory . CreateProperty ( key , value , destructureObject ) ;
89- logEvent . AddPropertyIfAbsent ( property ) ;
103+ else
104+ AddProperty ( stateProperty ) ;
90105 }
91106 }
92107 else
0 commit comments