From: Stephen Toub Date: Sat, 9 Jun 2018 02:53:52 +0000 (-0400) Subject: Use cached strings for values 0 to 9 (dotnet/coreclr#18383) X-Git-Tag: submit/tizen/20210909.063632~11030^2~4638 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=d005d280816e05d96b969501521e4c99e50ab119;p=platform%2Fupstream%2Fdotnet%2Fruntime.git Use cached strings for values 0 to 9 (dotnet/coreclr#18383) When doing ToString on single-digit integers, just return a cached string. This helps avoid string allocation/formatting costs for this very common case, while only costing one comparison for other cases. Commit migrated from https://github.com/dotnet/coreclr/commit/12f8a27b139777e8cee7ae924c0b71f5844f96f8 --- diff --git a/src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs b/src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs index 387fe01..1ff6982 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs @@ -251,6 +251,8 @@ namespace System private const int CharStackBufferSize = 32; private const string PosNumberFormat = "#"; + private static readonly string[] s_singleDigitStringCache = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; + private static readonly string[] s_posCurrencyFormats = { "$#", "#$", "$ #", "# $" @@ -1095,6 +1097,13 @@ namespace System private static unsafe string UInt32ToDecStr(uint value, int digits) { int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)); + + // For single-digit values that are very common, especially 0 and 1, just return cached strings. + if (bufferLength == 1) + { + return s_singleDigitStringCache[value]; + } + string result = string.FastAllocateString(bufferLength); fixed (char* buffer = result) { @@ -1339,6 +1348,13 @@ namespace System digits = 1; int bufferLength = Math.Max(digits, FormattingHelpers.CountDigits(value)); + + // For single-digit values that are very common, especially 0 and 1, just return cached strings. + if (bufferLength == 1) + { + return s_singleDigitStringCache[value]; + } + string result = string.FastAllocateString(bufferLength); fixed (char* buffer = result) {