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

Improve string comparison performance #1299

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

Nice3point
Copy link
Contributor

@Nice3point Nice3point commented Dec 25, 2024

The current version of the comparison is extremely inefficient. As you know ToLower is a rather slow operation, which may reduce performance for comparing a large number of strings. The best way is to use overloading with StringComparison support. But it is not available in Net framework.

I added the code and description from .Net 9 to support the method on any target framework. To prevent using from being marked unused in Net core and accidentally deleted, I added global using for extensions in the UI package.

Additionally I removed the Trim call, for URI comparison, URI does not support spaces and such call is useless, every call I debugged, everything compares correctly, previous behaviour is preserved with performance increase.

Before:

"text".Trim().ToLower().Contains("Text")

Now:

"text".Contains("Text", StringComparison.OrdinalIgnoreCase)

Benchmark for string pack://application:,,,/Wpf.Ui;component/Resources/Theme/Light.xaml:

Method Mean Error StdDev Allocated
ToLower 37.22 ns 2.117 ns 3.103 ns 160 B
OrdinalIgnoreCase 13.61 ns 0.138 ns 0.203 ns -
InvariantCultureIgnoreCase 92.63 ns 0.656 ns 0.962 ns -

StringComparison.OrdinalIgnoreCase 3 times faster without memory allocation.

Pull request type

Please check the type of change your PR introduces:

  • Update
  • Bugfix
  • Feature
  • Code style update (formatting, renaming)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • Documentation content changes

@github-actions github-actions bot added themes Topic is related to managing themes controls Changes to the appearance or logic of custom controls. PR Pull request icons Fonts and icons updates dotnet release titlebar Titlebar updates labels Dec 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
controls Changes to the appearance or logic of custom controls. dotnet icons Fonts and icons updates PR Pull request release themes Topic is related to managing themes titlebar Titlebar updates
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant