Short-circuit for empty strings in Insert/Remove
authorJames Ko <jamesqko@gmail.com>
Sun, 21 Feb 2016 02:44:23 +0000 (21:44 -0500)
committerJames Ko <jamesqko@gmail.com>
Sun, 21 Feb 2016 02:44:23 +0000 (21:44 -0500)
Commit migrated from https://github.com/dotnet/coreclr/commit/74709851898330c6ac3a20eb04d085e9b0e2dcf0

src/coreclr/src/mscorlib/src/System/String.cs

index 72089b0..5e443a8 100644 (file)
@@ -2851,12 +2851,17 @@ namespace System {
             Contract.Ensures(Contract.Result<String>() != null);
             Contract.Ensures(Contract.Result<String>().Length == this.Length + value.Length);
             Contract.EndContractBlock();
+            
             int oldLength = Length;
             int insertLength = value.Length;
+            
+            if (oldLength == 0)
+                return value;
+            if (insertLength == 0)
+                return this;
+            
             // In case this computation overflows, newLength will be negative and FastAllocateString throws OutOfMemoryException
             int newLength = oldLength + insertLength;
-            if (newLength == 0)
-                return String.Empty;
             String result = FastAllocateString(newLength);
             unsafe
             {
@@ -2937,9 +2942,13 @@ namespace System {
             Contract.Ensures(Contract.Result<String>() != null);
             Contract.Ensures(Contract.Result<String>().Length == this.Length - count);
             Contract.EndContractBlock();
+            
+            if (count == 0)
+                return this;
             int newLength = Length - count;
             if (newLength == 0)
                 return String.Empty;
+            
             String result = FastAllocateString(newLength);
             unsafe
             {