Skip to content

Commit 3fc26f0

Browse files
committed
Minor performance improvement for Set(ref T) overload
1 parent 4be1471 commit 3fc26f0

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

Microsoft.Toolkit.Mvvm/ComponentModel/ObservableObject.cs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,26 @@ protected virtual void OnPropertyChanging([CallerMemberName] string? propertyNam
6666
/// </remarks>
6767
protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName] string? propertyName = null)
6868
{
69-
return SetProperty(ref field, newValue, EqualityComparer<T>.Default, propertyName);
69+
// We duplicate the code here instead of calling the overload because we can't
70+
// guarantee that the invoked SetProperty<T> will be inlined, and we need the JIT
71+
// to be able to see the full EqualityComparer<T>.Default.Equals call, so that
72+
// it'll use the intrinsics version of it and just replace the whole invocation
73+
// with a direct comparison when possible (eg. for primitive numeric types).
74+
// This is the fastest SetProperty<T> overload so we particularly care about
75+
// the codegen quality here, and the code is small and simple enough so that
76+
// duplicating it still doesn't make the whole class harder to maintain.
77+
if (EqualityComparer<T>.Default.Equals(field, newValue))
78+
{
79+
return false;
80+
}
81+
82+
OnPropertyChanging(propertyName);
83+
84+
field = newValue;
85+
86+
OnPropertyChanged(propertyName);
87+
88+
return true;
7089
}
7190

7291
/// <summary>

0 commit comments

Comments
 (0)