Skip to content

Commit e935780

Browse files
authored
Fast-path in String.Trim (#84300)
1 parent bc887b3 commit e935780

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/libraries/System.Private.CoreLib/src/System/String.Manipulation.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2142,10 +2142,24 @@ public string ToUpperInvariant()
21422142
// Trims the whitespace from both ends of the string. Whitespace is defined by
21432143
// char.IsWhiteSpace.
21442144
//
2145-
public string Trim() => TrimWhiteSpaceHelper(TrimType.Both);
2145+
public string Trim()
2146+
{
2147+
if (Length == 0 || (!char.IsWhiteSpace(_firstChar) && !char.IsWhiteSpace(this[^1])))
2148+
{
2149+
return this;
2150+
}
2151+
return TrimWhiteSpaceHelper(TrimType.Both);
2152+
}
21462153

21472154
// Removes a set of characters from the beginning and end of this string.
2148-
public unsafe string Trim(char trimChar) => TrimHelper(&trimChar, 1, TrimType.Both);
2155+
public unsafe string Trim(char trimChar)
2156+
{
2157+
if (Length == 0 || (_firstChar != trimChar && this[^1] != trimChar))
2158+
{
2159+
return this;
2160+
}
2161+
return TrimHelper(&trimChar, 1, TrimType.Both);
2162+
}
21492163

21502164
// Removes a set of characters from the beginning and end of this string.
21512165
public unsafe string Trim(params char[]? trimChars)

0 commit comments

Comments
 (0)