Fast-path in String.Trim (#84300)
authorEgor Bogatov <egorbo@gmail.com>
Tue, 4 Apr 2023 20:55:52 +0000 (22:55 +0200)
committerGitHub <noreply@github.com>
Tue, 4 Apr 2023 20:55:52 +0000 (22:55 +0200)
src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs

index b28c0601f4138012deb77f50a42a9886e7595a36..2aa86a75d80420dd882af813b9f7b001c121aa05 100644 (file)
@@ -2142,10 +2142,24 @@ namespace System
         // Trims the whitespace from both ends of the string.  Whitespace is defined by
         // char.IsWhiteSpace.
         //
-        public string Trim() => TrimWhiteSpaceHelper(TrimType.Both);
+        public string Trim()
+        {
+            if (Length == 0 || (!char.IsWhiteSpace(_firstChar) && !char.IsWhiteSpace(this[^1])))
+            {
+                return this;
+            }
+            return TrimWhiteSpaceHelper(TrimType.Both);
+        }
 
         // Removes a set of characters from the beginning and end of this string.
-        public unsafe string Trim(char trimChar) => TrimHelper(&trimChar, 1, TrimType.Both);
+        public unsafe string Trim(char trimChar)
+        {
+            if (Length == 0 || (_firstChar != trimChar && this[^1] != trimChar))
+            {
+                return this;
+            }
+            return TrimHelper(&trimChar, 1, TrimType.Both);
+        }
 
         // Removes a set of characters from the beginning and end of this string.
         public unsafe string Trim(params char[]? trimChars)