Use cached strings for values 0 to 9 (dotnet/coreclr#18383)
authorStephen Toub <stoub@microsoft.com>
Sat, 9 Jun 2018 02:53:52 +0000 (22:53 -0400)
committerGitHub <noreply@github.com>
Sat, 9 Jun 2018 02:53:52 +0000 (22:53 -0400)
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

src/libraries/System.Private.CoreLib/src/System/Number.Formatting.cs

index 387fe01..1ff6982 100644 (file)
@@ -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)
             {