/
aprogrammer
/
serilog
Обзор
Документация
Войти
/
aprogrammer
/
serilog
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
dev
test/Serilog.PerformanceTests/Support/DictionaryMessageTemplateCache.cs
50 строк
2 KB
Evgeny Peshkov
By reference string comparison in template cache (#1947)
09 окт 2023, 10:05
Не верифицирован
09 окт 2023, 10:05
88f76a8
Код
Авторство
О чём код?
namespace Serilog.PerformanceTests.Support; class DictionaryMessageTemplateCache : IMessageTemplateParser { readonly IMessageTemplateParser _innerParser; readonly object _templatesLock = new(); readonly Dictionary<string, MessageTemplate> _templates = new(ByReferenceStringComparer.Instance); const int MaxCacheItems = 1000; const int MaxCachedTemplateLength = 1024; public DictionaryMessageTemplateCache(IMessageTemplateParser innerParser) { _innerParser = Guard.AgainstNull(innerParser); } public MessageTemplate Parse(string messageTemplate) { Guard.AgainstNull(messageTemplate); if (messageTemplate.Length > MaxCachedTemplateLength) return _innerParser.Parse(messageTemplate); MessageTemplate? result; lock (_templatesLock) if (_templates.TryGetValue(messageTemplate, out result)) return result; result = _innerParser.Parse(messageTemplate); lock (_templatesLock) { // Exceeding MaxCacheItems is *not* the sunny day scenario; all we're doing here is preventing out-of-memory // conditions when the library is used incorrectly. Correct use (templates, rather than // direct message strings) should barely, if ever, overflow this cache. // Changing workloads through the lifecycle of an app instance mean we can gain some ground by // potentially dropping templates generated only in startup, or only during specific infrequent // activities. if (_templates.Count == MaxCacheItems) _templates.Clear(); _templates[messageTemplate] = result; } return result; } }