From 90ea988aafb0cb83681c787fea1fd0b78b628104 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 7 Feb 2024 21:10:03 +1100 Subject: [PATCH] cache _timeUnits --- src/Humanizer/TimeSpanHumanizeExtensions.cs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/src/Humanizer/TimeSpanHumanizeExtensions.cs b/src/Humanizer/TimeSpanHumanizeExtensions.cs index 4fd5a0437..91493f33a 100644 --- a/src/Humanizer/TimeSpanHumanizeExtensions.cs +++ b/src/Humanizer/TimeSpanHumanizeExtensions.cs @@ -17,6 +17,11 @@ public static class TimeSpanHumanizeExtensions private const double _daysInAYear = 365.2425; // see https://en.wikipedia.org/wiki/Gregorian_calendar private const double _daysInAMonth = _daysInAYear / 12; + static TimeUnit[] _timeUnits = Enum.GetValues(typeof(TimeUnit)) + .Cast() + .Reverse() + .ToArray(); + /// /// Turns a TimeSpan into a human readable form. E.g. 1 day. /// @@ -57,17 +62,16 @@ private static IEnumerable CreateTheTimePartsWithUpperAndLowerLimits(Tim { var cultureFormatter = Configurator.GetFormatter(culture); var firstValueFound = false; - var timeUnitsEnumTypes = GetEnumTypesForTimeUnit(); var timeParts = new List(); - foreach (var timeUnitType in timeUnitsEnumTypes) + foreach (var timeUnit in _timeUnits) { - var timepart = GetTimeUnitPart(timeUnitType,timespan, maxUnit, minUnit, cultureFormatter, toWords); + var timePart = GetTimeUnitPart(timeUnit, timespan, maxUnit, minUnit, cultureFormatter, toWords); - if (timepart != null || firstValueFound) + if (timePart != null || firstValueFound) { firstValueFound = true; - timeParts.Add(timepart); + timeParts.Add(timePart); } } if (IsContainingOnlyNullValue(timeParts)) @@ -79,12 +83,6 @@ private static IEnumerable CreateTheTimePartsWithUpperAndLowerLimits(Tim return timeParts; } - private static IEnumerable GetEnumTypesForTimeUnit() - { - var enumTypeEnumerator = (IEnumerable)Enum.GetValues(typeof(TimeUnit)); - return enumTypeEnumerator.Reverse(); - } - private static string GetTimeUnitPart(TimeUnit timeUnitToGet, TimeSpan timespan, TimeUnit maximumTimeUnit, TimeUnit minimumTimeUnit, IFormatter cultureFormatter, bool toWords = false) { if (timeUnitToGet <= maximumTimeUnit && timeUnitToGet >= minimumTimeUnit)