Improve Clamp() performance#20051
Conversation
|
Hey there @symbiogenesis! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
1a89f5a to
23dfcd7
Compare
23dfcd7 to
8c48abe
Compare
3719619 to
e80e4ea
Compare
e80e4ea to
9c822f2
Compare
|
Fixing the build, and aligning the ambiguous namespace resolution issue with PR #19965, which should be cleaner |
6256bee to
787ed11
Compare
|
Loving your performance improvement PRs! Thank you!🙏 |
461307f to
dec28a0
Compare
6262854 to
682bdd2
Compare
682bdd2 to
17bac71
Compare
|
Ok, so I just noticed that there's double.Clamp() and float.Clamp() but they don't seem to use the same aggressive optimization techniques of Math.Clamp(). But I added them, because their performance was as good as anything else. |
| public static T Clamp<T>(this T value, T min, T max) where T : IComparable<T> | ||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
| public static DateTime Clamp(this DateTime value, DateTime min, DateTime max) |
There was a problem hiding this comment.
So one thing to note is that [MethodImpl(MethodImplOptions.AggressiveInlining)] increases app size as the AOT images will be larger (libaot-Microsoft.Maui.Graphics.dll.so).
I would maybe not add it here if you didn't see it specifically improve something.
| #if NETSTANDARD2_1_OR_GREATER | ||
| using System; | ||
| #endif |
There was a problem hiding this comment.
Doesn't seem like the #if expressions here are needed.
| { | ||
| #if NETCOREAPP3_0_OR_GREATER | ||
| return double.Clamp(self, min, max); | ||
| #else |
There was a problem hiding this comment.
Reading the docs, I think double/float.Clamp() were introduced in .NET 7?
https://learn.microsoft.com/en-us/dotnet/api/system.double.clamp?view=net-7.0
| using System.Runtime.CompilerServices; | ||
|
|
||
| [assembly: InternalsVisibleTo("iOSUnitTests")] | ||
| [assembly: InternalsVisibleTo("Microsoft.Maui")] |
There was a problem hiding this comment.
Do we need to add this file, or can it be removed?
The current Clamp() extension based on IComparable is about twice as slow for floats and doubles, and was being used in at least 35 places.
It is just an internal function that was not used on anything interesting that implements IComparable. It only was used on int, double, and float types. And one DateTime.
The most critical path for clamp is probably Color.cs
There already was another NumericExtensions class in the Graphics assembly for dealing with those types. Replicating the use of AggressiveInlining on the IComparable implementation, to align with NumericExtensions, doesn't change much about the results.
There is also Math.Clamp(), but it only exists on .NET Standard 2.1 and above. It allocates less for ints, but NumericExtensions is slightly better otherwise.
There is no MathF.Clamp() for floats, unfortunately.