Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fast-path in String.Trim #84300

Merged
merged 2 commits into from
Apr 4, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2142,10 +2142,24 @@ public string ToUpperInvariant()
// 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))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No bound checks here due to #84213

{
return this;
}
return TrimHelper(&trimChar, 1, TrimType.Both);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not for this PR, but now that we'll be invoking these helpers only when we know there is something to be trimmed, I wonder whether employing an IndexOfAnyExceptWhitespace would be more useful, i.e. whether there being any whitespace makes it more likely there's enough whitespace for vectorization to be a win.

}

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