diff --git a/Source/ReactiveProperty.Core/Internals/PropertyPathAccessor.cs b/Source/ReactiveProperty.Core/Internals/PropertyPathAccessor.cs new file mode 100644 index 00000000..eee38908 --- /dev/null +++ b/Source/ReactiveProperty.Core/Internals/PropertyPathAccessor.cs @@ -0,0 +1,64 @@ +using System; +using System.Linq.Expressions; +using System.Reflection; +using System.Runtime.CompilerServices; + +namespace Reactive.Bindings.Internals; + +internal static class PropertyPathAccessor +{ + private static readonly ConditionalWeakTable> s_getters = new(); + private static readonly ConditionalWeakTable> s_setters = new(); + + public static Func Get(Delegate accessor) => s_getters.GetValue(accessor, CreateGetter); + + public static Action Set(Delegate accessor) => s_setters.GetValue(accessor, CreateSetter); + + private static Func CreateGetter(Delegate accessor) + { + var typeArguments = accessor.GetType().GetGenericArguments(); + var source = Expression.Parameter(typeof(object), "source"); + var invoke = Expression.Invoke(Expression.Constant(accessor), Expression.Convert(source, typeArguments[0])); + var fallback = Expression.Call( + Expression.Constant(accessor), + nameof(Delegate.DynamicInvoke), + Type.EmptyTypes, + Expression.NewArrayInit(typeof(object), source)); + var body = Expression.Condition( + Expression.TypeIs(source, typeArguments[0]), + Expression.Convert(WrapTargetExceptions(invoke), typeof(object)), + fallback); + return Expression.Lambda>(body, source).Compile(); + } + + private static Action CreateSetter(Delegate accessor) + { + var typeArguments = accessor.GetType().GetGenericArguments(); + var source = Expression.Parameter(typeof(object), "source"); + var value = Expression.Parameter(typeof(object), "value"); + var invoke = Expression.Invoke( + Expression.Constant(accessor), + Expression.Convert(source, typeArguments[0]), + Expression.Convert(value, typeArguments[1])); + var fallback = Expression.Call( + Expression.Constant(accessor), + nameof(Delegate.DynamicInvoke), + Type.EmptyTypes, + Expression.NewArrayInit(typeof(object), source, value)); + var body = Expression.IfThenElse( + Expression.AndAlso(Expression.TypeIs(source, typeArguments[0]), Expression.TypeIs(value, typeArguments[1])), + WrapTargetExceptions(invoke), + Expression.Block(fallback, Expression.Empty())); + return Expression.Lambda>(body, source, value).Compile(); + } + + private static Expression WrapTargetExceptions(Expression invoke) + { + var exception = Expression.Parameter(typeof(Exception), "exception"); + var constructor = typeof(TargetInvocationException).GetConstructor(new[] { typeof(Exception) })!; + // DynamicInvoke wraps exceptions thrown by the target delegate. + return Expression.TryCatch( + invoke, + Expression.Catch(exception, Expression.Throw(Expression.New(constructor, exception), invoke.Type))); + } +} diff --git a/Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs b/Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs index 4017bdf4..8ae1e7ef 100644 --- a/Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs +++ b/Source/ReactiveProperty.Core/Internals/PropertyPathNode.cs @@ -8,8 +8,8 @@ internal class PropertyPathNode : IDisposable { private bool _isDisposed = false; private Action? _callback; - private Delegate? _getAccessor; - private Delegate? _setAccessor; + private Func? _getAccessor; + private Action? _setAccessor; public event EventHandler? PropertyChanged; @@ -69,8 +69,8 @@ private void StartObservePropertyChanged() { EnsureDispose(); if (Source == null) return null; - return (_getAccessor ?? (_getAccessor = AccessorCache.LookupGet(Source.GetType(), PropertyName))) - .DynamicInvoke(Source); + return (_getAccessor ?? (_getAccessor = PropertyPathAccessor.Get(AccessorCache.LookupGet(Source.GetType(), PropertyName)))) + .Invoke(Source); } public object? GetPropertyPathValue() @@ -101,8 +101,8 @@ public bool SetPropertyPathValue(object? value) } else { - var setter = _setAccessor ?? (_setAccessor = AccessorCache.LookupSet(Source.GetType(), PropertyName)); - setter.DynamicInvoke(Source, value); + var setter = _setAccessor ?? (_setAccessor = PropertyPathAccessor.Set(AccessorCache.LookupSet(Source.GetType(), PropertyName))); + setter(Source, value); return true; } } diff --git a/Source/ReactiveProperty.Core/ValidatableReactiveProperty.cs b/Source/ReactiveProperty.Core/ValidatableReactiveProperty.cs index b0c231a8..e1eb221f 100644 --- a/Source/ReactiveProperty.Core/ValidatableReactiveProperty.cs +++ b/Source/ReactiveProperty.Core/ValidatableReactiveProperty.cs @@ -337,9 +337,17 @@ private void Validate(T value, ValidationKind validationKind = ValidationKind.De _latestValue = value; if (needValidation) { - _errorMessages.Value = _validators.Select(x => x(value)) - .Where(x => x is not null) - .ToArray()!; + List? errors = null; + foreach (var validator in _validators) + { + var error = validator(value); + if (error is not null) + { + (errors ??= []).Add(error); + } + } + + _errorMessages.Value = errors?.ToArray() ?? []; } if (isNotEquals || IsDistinctUntilChanged is false) diff --git a/Source/ReactiveProperty.NETStandard/Internals/PropertyPathNodeLegacy.cs b/Source/ReactiveProperty.NETStandard/Internals/PropertyPathNodeLegacy.cs index 3071da11..f9f804d0 100644 --- a/Source/ReactiveProperty.NETStandard/Internals/PropertyPathNodeLegacy.cs +++ b/Source/ReactiveProperty.NETStandard/Internals/PropertyPathNodeLegacy.cs @@ -9,8 +9,8 @@ internal class PropertyPathNodeLegacy : IDisposable { private bool _isDisposed = false; private Action? _callback; - private Delegate? _getAccessor; - private Delegate? _setAccessor; + private Func? _getAccessor; + private Action? _setAccessor; public event EventHandler? PropertyChanged; @@ -70,8 +70,8 @@ private void StartObservePropertyChanged() { EnsureDispose(); if (Source == null) return null; - return (_getAccessor ?? (_getAccessor = AccessorCache.LookupGet(Source.GetType(), PropertyName))) - .DynamicInvoke(Source); + return (_getAccessor ?? (_getAccessor = PropertyPathAccessor.Get(AccessorCache.LookupGet(Source.GetType(), PropertyName)))) + .Invoke(Source); } public object? GetPropertyPathValue() @@ -102,8 +102,8 @@ public bool SetPropertyPathValue(object? value) } else { - var setter = _setAccessor ?? (_setAccessor = AccessorCache.LookupSet(Source.GetType(), PropertyName)); - setter.DynamicInvoke(Source, value); + var setter = _setAccessor ?? (_setAccessor = PropertyPathAccessor.Set(AccessorCache.LookupSet(Source.GetType(), PropertyName))); + setter(Source, value); return true; } } diff --git a/Source/ReactiveProperty.R3/Extensions/FilteredReadOnlyObservableCollection.cs b/Source/ReactiveProperty.R3/Extensions/FilteredReadOnlyObservableCollection.cs index 0de0c253..091f743b 100644 --- a/Source/ReactiveProperty.R3/Extensions/FilteredReadOnlyObservableCollection.cs +++ b/Source/ReactiveProperty.R3/Extensions/FilteredReadOnlyObservableCollection.cs @@ -29,6 +29,9 @@ internal sealed class FilteredReadOnlyObservableCollection where TElement : class, INotifyPropertyChanged { + private static readonly PropertyChangedEventArgs s_countPropertyChangedEventArgs = new(nameof(Count)); + private static readonly PropertyChangedEventArgs s_indexerPropertyChangedEventArgs = new("Item[]"); + private readonly object _syncRoot = new(); private readonly List _innerCollection = new(); private readonly List _indexList = new(); @@ -178,7 +181,7 @@ private void SourceCollectionChanged(object? sender, NotifyCollectionChangedEven { var sourceIndex = e.OldStartingIndex; var filteredIndex = _indexList[sourceIndex]; - var item = e.OldItems.Cast().ElementAt(i); + var item = (TElement)e.OldItems[i]!; if (filteredIndex.HasValue) { DisappearItem(sourceIndex); @@ -312,8 +315,8 @@ private void RaiseChangedCore(NotifyCollectionChangedEventArgs? args) return; } - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]")); + PropertyChanged?.Invoke(this, s_countPropertyChangedEventArgs); + PropertyChanged?.Invoke(this, s_indexerPropertyChangedEventArgs); CollectionChanged?.Invoke(this, args); } } diff --git a/Source/ReactiveProperty.R3/ReadOnlyReactiveCollection.cs b/Source/ReactiveProperty.R3/ReadOnlyReactiveCollection.cs index 36cd7633..b6ec3171 100644 --- a/Source/ReactiveProperty.R3/ReadOnlyReactiveCollection.cs +++ b/Source/ReactiveProperty.R3/ReadOnlyReactiveCollection.cs @@ -16,6 +16,9 @@ namespace Reactive.Bindings.R3; /// Element type. public sealed class ReadOnlyReactiveCollection : ReadOnlyObservableCollection, IDisposable { + private static readonly PropertyChangedEventArgs s_countPropertyChangedEventArgs = new(nameof(Count)); + private static readonly PropertyChangedEventArgs s_indexerPropertyChangedEventArgs = new("Item[]"); + private readonly object _syncRoot = new(); private readonly ObservableCollection _source; private readonly bool _disposeElement; @@ -145,8 +148,8 @@ private void ApplyCollectionChangedCore(CollectionChanged collectionChanged) } } - OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count))); - OnPropertyChanged(new PropertyChangedEventArgs("Item[]")); + OnPropertyChanged(s_countPropertyChangedEventArgs); + OnPropertyChanged(s_indexerPropertyChangedEventArgs); OnCollectionChanged(eventArgs); } diff --git a/Source/ReactiveProperty.R3/ValidatableReactiveProperty.cs b/Source/ReactiveProperty.R3/ValidatableReactiveProperty.cs index 1fa38326..003d90fb 100644 --- a/Source/ReactiveProperty.R3/ValidatableReactiveProperty.cs +++ b/Source/ReactiveProperty.R3/ValidatableReactiveProperty.cs @@ -18,13 +18,17 @@ namespace Reactive.Bindings.R3; /// Value type. public sealed class ValidatableReactiveProperty : Observable, INotifyPropertyChanged, INotifyDataErrorInfo, IDisposable { + private static readonly PropertyChangedEventArgs s_valuePropertyChangedEventArgs = new(nameof(Value)); + private static readonly PropertyChangedEventArgs s_errorMessagePropertyChangedEventArgs = new(nameof(ErrorMessage)); + private static readonly PropertyChangedEventArgs s_hasErrorsPropertyChangedEventArgs = new(nameof(HasErrors)); + private readonly ReactiveProperty _property; private readonly IEqualityComparer _equalityComparer; private readonly object _validationSyncRoot = new(); private readonly ReactiveProperty> _errors = new(Array.Empty()); private readonly ReactiveProperty _hasErrors = new(false); private readonly Subject _validationTrigger = new(); - private readonly List<(int Slot, Func?> Validate)> _validators = new(); + private (int Slot, Func?> Validate)[] _validators = []; private readonly List _validationErrors = new(); private readonly List _subscriptions = new(); private readonly bool _ignoreInitialValidationError; @@ -60,7 +64,7 @@ public T Value _hasChangedValue = true; _property.Value = value; ValidateAndNotify(value); - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Value))); + PropertyChanged?.Invoke(this, s_valuePropertyChangedEventArgs); } } @@ -134,7 +138,11 @@ public ValidatableReactiveProperty SetValidateNotifyError(Func?> Validate)[validators.Length + 1]; + Array.Copy(validators, nextValidators, validators.Length); + nextValidators[validators.Length] = (slot, validate); + _validators = nextValidators; } ValidateAfterRegistration(); @@ -285,7 +293,7 @@ private void Validate(T value) (int Slot, Func?> Validate)[] validators; lock (_validationSyncRoot) { - validators = [.. _validators]; + validators = _validators; } if (validators.Length == 0) @@ -309,7 +317,13 @@ private void SetErrors(int slot, IEnumerable errors) { lock (_validationSyncRoot) { - _validationErrors[slot] = [.. errors]; + string[] nextErrors = [.. errors]; + if (_validationErrors[slot].SequenceEqual(nextErrors) && ErrorsMatchSlots()) + { + return; + } + + _validationErrors[slot] = nextErrors; string[] next = [.. _validationErrors.SelectMany(static x => x)]; var previousHasErrors = _hasErrors.Value; if (_errors.Value.SequenceEqual(next)) @@ -320,12 +334,32 @@ private void SetErrors(int slot, IEnumerable errors) _errors.Value = next; _hasErrors.Value = next.Length != 0; ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Value))); - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ErrorMessage))); + PropertyChanged?.Invoke(this, s_errorMessagePropertyChangedEventArgs); if (previousHasErrors != _hasErrors.Value) { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasErrors))); + PropertyChanged?.Invoke(this, s_hasErrorsPropertyChangedEventArgs); + } + } + } + + private bool ErrorsMatchSlots() + { + var current = _errors.Value; + var index = 0; + foreach (var errors in _validationErrors) + { + foreach (var error in errors) + { + if (index >= current.Count || !EqualityComparer.Default.Equals(error, current[index])) + { + return false; + } + + index++; } } + + return index == current.Count; } private static string[] ToErrorMessages(IEnumerable? errors) diff --git a/Test/ReactiveProperty.NETStandard.Tests/Internals/PropertyObservableTest.cs b/Test/ReactiveProperty.NETStandard.Tests/Internals/PropertyObservableTest.cs index 6ff68fe8..bea7ba5b 100644 --- a/Test/ReactiveProperty.NETStandard.Tests/Internals/PropertyObservableTest.cs +++ b/Test/ReactiveProperty.NETStandard.Tests/Internals/PropertyObservableTest.cs @@ -1,6 +1,9 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.ComponentModel; +using System.Reflection; using System.Runtime.CompilerServices; +using System.Threading.Tasks; using Microsoft.Reactive.Testing; using Microsoft.VisualStudio.TestTools.UnitTesting; using Reactive.Bindings; @@ -11,6 +14,175 @@ namespace ReactiveProperty.Tests.Internals; [TestClass] public class PropertyObservableTest : ReactiveTest { + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PathAccessorPreservesNullAndReflectionConversions(bool legacy) + { + var source = new AccessorItem(); + using var node = new PathNodeHarness(legacy, nameof(AccessorItem.Number)); + node.Update(source); + + node.Set((short)7).IsTrue(); + source.Number.Is(7); + node.Set(null).IsTrue(); + source.Number.Is(0); + Assert.ThrowsExactly(() => node.Set("invalid")); + + node.Update(null); + node.Get().IsNull(); + node.Set(1).IsFalse(); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PathAccessorPreservesNullableAndBoxedStructValues(bool legacy) + { + var source = new AccessorItem(); + using var nullable = new PathNodeHarness(legacy, nameof(AccessorItem.Optional)); + nullable.Update(source); + nullable.Set(5).IsTrue(); + source.Optional.Is(5); + nullable.Set(null).IsTrue(); + Assert.IsNull(source.Optional); + + object boxed = new AccessorStruct { Number = 1 }; + using var valueType = new PathNodeHarness(legacy, nameof(AccessorStruct.Number)); + valueType.Update(boxed); + valueType.Get().Is(1); + valueType.Set(2).IsTrue(); + ((AccessorStruct)boxed).Number.Is(1); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PathAccessorPreservesGetterAndSetterExceptions(bool legacy) + { + using var node = new PathNodeHarness(legacy, nameof(ThrowingItem.Value)); + node.Update(new ThrowingItem()); + + var getError = Assert.ThrowsExactly(() => node.Get()); + Assert.IsInstanceOfType(getError.InnerException); + var setError = Assert.ThrowsExactly(() => node.Set(1)); + Assert.IsInstanceOfType(setError.InnerException); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void PathAccessorPreservesMissingMembersAndChangedSourceType(bool legacy) + { + using var missing = new PathNodeHarness(legacy, "Missing"); + missing.Update(new AccessorItem()); + Assert.ThrowsExactly(() => missing.Get()); + + using var node = new PathNodeHarness(legacy, nameof(AccessorItem.Number)); + node.Update(new AccessorItem()); + node.Set(1).IsTrue(); + node.Update(new OtherAccessorItem { Number = 9 }); + node.Get().Is(9); + Assert.ThrowsExactly(() => node.Set(2)); + } + + [TestMethod] + [DataRow(false)] + [DataRow(true)] + public void RepeatedPathReadsAvoidExcessAllocation(bool legacy) + { + using var node = new PathNodeHarness(legacy, nameof(AccessorItem.Text)); + node.Update(new AccessorItem()); + for (var i = 0; i < 32; i++) + { + GC.KeepAlive(node.Get()); + } + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 64; i++) + { + GC.KeepAlive(node.Get()); + } + + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.IsTrue(allocated < 64 * 8, $"Allocated {allocated} bytes for 64 path reads."); + } + + [TestMethod] + public void PathAccessorCacheSupportsConcurrentFirstUse() + { + Parallel.For(0, 64, i => + { + var source = new ConcurrentAccessorItem { Number = i }; + using var node = new PathNodeHarness(i % 2 == 0, nameof(ConcurrentAccessorItem.Number)); + node.Update(source); + Assert.AreEqual(i, node.Get()); + Assert.IsTrue(node.Set(i + 1)); + Assert.AreEqual(i + 1, source.Number); + }); + } + + private sealed class PathNodeHarness : IDisposable + { + public readonly Action Update; + public readonly Func Get; + public readonly Func Set; + private readonly IDisposable _node; + + public PathNodeHarness(bool legacy, string propertyName) + { + if (legacy) + { + var node = new PropertyPathNodeLegacy(propertyName); + _node = node; + Update = node.UpdateSource; + Get = node.GetPropertyPathValue; + Set = node.SetPropertyPathValue; + } + else + { + var node = new PropertyPathNode(propertyName); + _node = node; + Update = node.UpdateSource; + Get = node.GetPropertyPathValue; + Set = node.SetPropertyPathValue; + } + } + + public void Dispose() => _node.Dispose(); + } + + private sealed class AccessorItem + { + public int Number { get; set; } + public int? Optional { get; set; } + public string Text { get; set; } = "value"; + } + + private struct AccessorStruct + { + public int Number { get; set; } + } + + private sealed class OtherAccessorItem + { + public int Number { get; set; } + } + + private sealed class ConcurrentAccessorItem + { + public int Number { get; set; } + } + + private sealed class ThrowingItem + { + public int Value + { + get => throw new InvalidOperationException("getter"); + set => throw new InvalidOperationException("setter"); + } + } + [TestMethod] public void ObserveProperty() { diff --git a/Test/ReactiveProperty.NETStandard.Tests/ValidatableReactivePropertyTest.cs b/Test/ReactiveProperty.NETStandard.Tests/ValidatableReactivePropertyTest.cs index 525ed1f8..55f9e41a 100644 --- a/Test/ReactiveProperty.NETStandard.Tests/ValidatableReactivePropertyTest.cs +++ b/Test/ReactiveProperty.NETStandard.Tests/ValidatableReactivePropertyTest.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Runtime.CompilerServices; @@ -13,6 +14,83 @@ namespace ReactiveProperty.Tests; [TestClass] public class ValidatableReactivePropertyTest : ReactiveTest { + [TestMethod] + [DataRow(0, 0)] + [DataRow(1, 0)] + [DataRow(1, 1)] + [DataRow(8, 0)] + [DataRow(8, 1)] + [DataRow(8, 2)] + public void ForceNotifyHandlesValidatorResults(int count, int errorMode) + { + var calls = 0; + var validators = Enumerable.Range(0, count) + .Select(i => (Func)(_ => + { + calls++; + return errorMode == 2 || (errorMode == 1 && i % 2 == 0) ? $"error-{i}" : null; + })) + .ToArray(); + using var target = new ValidatableReactiveProperty(0, validators); + calls = 0; + var expectedErrors = Enumerable.Range(0, count) + .Where(i => errorMode == 2 || (errorMode == 1 && i % 2 == 0)) + .Select(i => $"error-{i}") + .ToArray(); + + target.ForceNotify(); + + calls.Is(count); + CollectionAssert.AreEqual(expectedErrors, target.GetErrors()); + Assert.AreEqual(expectedErrors.Length != 0, target.HasErrors); + } + + [TestMethod] + public void ForceNotifyPreservesValidatorOrderAndEmptyStringErrors() + { + var calls = 0; + using var target = new ValidatableReactiveProperty( + 0, + new Func[] + { + _ => { calls++; return null; }, + _ => { calls++; return ""; }, + _ => { calls++; return "error"; }, + }); + + calls = 0; + target.ForceNotify(); + + calls.Is(3); + target.HasErrors.IsTrue(); + target.GetErrors().Is("", "error"); + } + + [TestMethod] + public void ForceNotifyWithNoErrorsAvoidsExcessAllocation() + { + using var target = new ValidatableReactiveProperty( + 0, + new Func[] + { + _ => null, _ => null, _ => null, _ => null, + _ => null, _ => null, _ => null, _ => null, + }); + for (var i = 0; i < 32; i++) + { + target.ForceNotify(); + } + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 64; i++) + { + target.ForceNotify(); + } + + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.IsTrue(allocated < 64 * 64, $"Allocated {allocated} bytes for 64 validations."); + } + [TestMethod] public void BasicUsage() { diff --git a/Test/ReactiveProperty.R3.Tests/FilteredReadOnlyObservableCollectionTest.cs b/Test/ReactiveProperty.R3.Tests/FilteredReadOnlyObservableCollectionTest.cs index 62ae5afc..cf33a39c 100644 --- a/Test/ReactiveProperty.R3.Tests/FilteredReadOnlyObservableCollectionTest.cs +++ b/Test/ReactiveProperty.R3.Tests/FilteredReadOnlyObservableCollectionTest.cs @@ -1,5 +1,7 @@ #nullable enable +using System; +using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; @@ -53,6 +55,136 @@ public void RaisesCollectionChangedOnProvidedSynchronizationContext() Assert.IsTrue(context.PostCount > 0); } + [TestMethod] + public void ReusesFixedPropertyChangedEventArgs() + { + var source = new ObservableCollection + { + new() { Name = "a", IsVisible = true }, + }; + var collection = source.ToFilteredReadOnlyObservableCollection(x => x.IsVisible); + var propertyChangedEvents = new List(); + collection.PropertyChanged += (_, e) => propertyChangedEvents.Add(e); + + source[0] = new Item { Name = "b", IsVisible = true }; + source[0] = new Item { Name = "c", IsVisible = true }; + + propertyChangedEvents.Select(static x => x.PropertyName).Is( + nameof(collection.Count), + "Item[]", + nameof(collection.Count), + "Item[]"); + Assert.AreSame(propertyChangedEvents[0], propertyChangedEvents[2]); + Assert.AreSame(propertyChangedEvents[1], propertyChangedEvents[3]); + } + + [TestMethod] + public void RangeRemovalAvoidsExcessAllocation() + { + var source = new RangeObservableCollection( + Enumerable.Range(0, 256).Select(_ => new Item { IsVisible = true })); + var collection = source.ToFilteredReadOnlyObservableCollection(x => x.IsVisible); + + var before = GC.GetAllocatedBytesForCurrentThread(); + source.RemoveRange(0, 256); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.AreEqual(0, collection.Count); + Assert.IsTrue(allocated < 15000, $"Range removal allocated {allocated} bytes."); + } + + [TestMethod] + [DataRow(0, RemovalVisibility.AllVisible)] + [DataRow(3, RemovalVisibility.AllVisible)] + [DataRow(5, RemovalVisibility.AllVisible)] + [DataRow(0, RemovalVisibility.NoneVisible)] + [DataRow(3, RemovalVisibility.NoneVisible)] + [DataRow(5, RemovalVisibility.NoneVisible)] + [DataRow(0, RemovalVisibility.Mixed)] + [DataRow(3, RemovalVisibility.Mixed)] + [DataRow(5, RemovalVisibility.Mixed)] + public void RangeRemovalPreservesItemsAndNotification(int startIndex, RemovalVisibility visibility) + { + var source = CreateRangeSource(startIndex, visibility); + var collection = source.ToFilteredReadOnlyObservableCollection(x => x.IsVisible); + var collectionChangedEvents = new List(); + var propertyChangedNames = new List(); + + collection.CollectionChanged += (_, e) => collectionChangedEvents.Add(e); + collection.PropertyChanged += (_, e) => propertyChangedNames.Add(e.PropertyName); + + var removedItems = source.Skip(startIndex).Take(2).ToArray(); + var firstRemovedTarget = removedItems.FirstOrDefault(x => x.IsVisible); + var filteredIndex = firstRemovedTarget is null + ? -1 + : source.Take(source.IndexOf(firstRemovedTarget)).Count(x => x.IsVisible); + + source.RemoveRange(startIndex, 2); + + var expectedNames = source.Where(x => x.IsVisible).Select(x => x.Name).ToArray(); + var actualNames = collection.Select(x => x.Name).ToArray(); + CollectionAssert.AreEqual(expectedNames, actualNames); + + if (firstRemovedTarget is null) + { + Assert.AreEqual(0, collectionChangedEvents.Count); + Assert.AreEqual(0, propertyChangedNames.Count); + return; + } + + Assert.AreEqual(1, collectionChangedEvents.Count); + var args = collectionChangedEvents[0]; + Assert.AreEqual(NotifyCollectionChangedAction.Remove, args.Action); + Assert.AreSame(firstRemovedTarget, args.OldItems![0]); + Assert.AreEqual(filteredIndex, args.OldStartingIndex); + CollectionAssert.AreEqual(new[] { nameof(collection.Count), "Item[]" }, propertyChangedNames); + } + + [TestMethod] + [DataRow(true)] + [DataRow(false)] + public void SingleItemRemovalPreservesItemsAndNotification(bool isVisible) + { + var source = new RangeObservableCollection( + Enumerable.Range(0, 5) + .Select(index => new Item { Name = $"item{index}", IsVisible = index == 2 ? isVisible : true })); + var collection = source.ToFilteredReadOnlyObservableCollection(x => x.IsVisible); + var collectionChangedEvents = new List(); + collection.CollectionChanged += (_, e) => collectionChangedEvents.Add(e); + var removedItem = source[2]; + var filteredIndex = source.Take(2).Count(x => x.IsVisible); + + source.RemoveRange(2, 1); + + CollectionAssert.AreEqual( + source.Where(x => x.IsVisible).Select(x => x.Name).ToArray(), + collection.Select(x => x.Name).ToArray()); + Assert.AreEqual(isVisible ? 1 : 0, collectionChangedEvents.Count); + if (isVisible) + { + Assert.AreEqual(NotifyCollectionChangedAction.Remove, collectionChangedEvents[0].Action); + Assert.AreSame(removedItem, collectionChangedEvents[0].OldItems![0]); + Assert.AreEqual(filteredIndex, collectionChangedEvents[0].OldStartingIndex); + } + } + + private static RangeObservableCollection CreateRangeSource(int startIndex, RemovalVisibility visibility) + { + var items = Enumerable.Range(0, 7) + .Select(index => new Item + { + Name = $"item{index}", + IsVisible = visibility switch + { + RemovalVisibility.AllVisible => true, + RemovalVisibility.NoneVisible => false, + RemovalVisibility.Mixed => index != startIndex, + _ => throw new AssertFailedException($"Unknown visibility case: {visibility}"), + }, + }); + return new RangeObservableCollection(items); + } + private sealed class TestSynchronizationContext : SynchronizationContext { public int PostCount { get; private set; } @@ -82,4 +214,36 @@ public bool IsVisible public event PropertyChangedEventHandler? PropertyChanged; } + + public enum RemovalVisibility + { + AllVisible, + NoneVisible, + Mixed, + } + + private sealed class RangeObservableCollection : ObservableCollection + { + public RangeObservableCollection(IEnumerable items) + : base(items.ToList()) + { + } + + public void RemoveRange(int index, int count) + { + var removedItems = new List(count); + for (var i = 0; i < count; i++) + { + removedItems.Add(Items[index]); + Items.RemoveAt(index); + } + + OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count))); + OnPropertyChanged(new PropertyChangedEventArgs("Item[]")); + OnCollectionChanged(new NotifyCollectionChangedEventArgs( + NotifyCollectionChangedAction.Remove, + (IList)removedItems, + index)); + } + } } diff --git a/Test/ReactiveProperty.R3.Tests/ReadOnlyReactiveCollectionTest.cs b/Test/ReactiveProperty.R3.Tests/ReadOnlyReactiveCollectionTest.cs index 390822a5..938dc730 100644 --- a/Test/ReactiveProperty.R3.Tests/ReadOnlyReactiveCollectionTest.cs +++ b/Test/ReactiveProperty.R3.Tests/ReadOnlyReactiveCollectionTest.cs @@ -64,6 +64,26 @@ public void RemoveReportsActualValueForValueTypeElements() removed[0].Is(10); } + [TestMethod] + public void ReusesFixedPropertyChangedEventArgs() + { + var source = new ObservableCollection { "a" }; + var collection = source.ToReadOnlyReactiveCollection(); + var propertyChangedEvents = new List(); + ((INotifyPropertyChanged)collection).PropertyChanged += (_, e) => propertyChangedEvents.Add(e); + + source[0] = "b"; + source[0] = "c"; + + propertyChangedEvents.Select(static x => x.PropertyName).Is( + nameof(collection.Count), + "Item[]", + nameof(collection.Count), + "Item[]"); + Assert.AreSame(propertyChangedEvents[0], propertyChangedEvents[2]); + Assert.AreSame(propertyChangedEvents[1], propertyChangedEvents[3]); + } + [TestMethod] public void AppliesObservableChangeStreamAndResetStream() { diff --git a/Test/ReactiveProperty.R3.Tests/ValidationTest.cs b/Test/ReactiveProperty.R3.Tests/ValidationTest.cs index e1138e8a..2ce96d6b 100644 --- a/Test/ReactiveProperty.R3.Tests/ValidationTest.cs +++ b/Test/ReactiveProperty.R3.Tests/ValidationTest.cs @@ -17,6 +17,98 @@ namespace ReactiveProperty.Tests; [TestClass] public sealed class ValidationTest { + [TestMethod] + public void RevalidatingUnchangedErrorsAvoidsExcessAllocation() + { + using var property = new ValidatableReactiveProperty(); + for (var i = 0; i < 8; i++) + { + property.SetValidateNotifyError(_ => (IEnumerable?)null); + } + + for (var i = 0; i < 32; i++) + { + property.ForceValidate(); + } + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 64; i++) + { + property.ForceValidate(); + } + + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + Assert.IsTrue(allocated < 64 * 256, $"Allocated {allocated} bytes for 64 validations."); + } + + [TestMethod] + public void RegisteringValidatorDuringValidationUsesStableSnapshot() + { + using var property = new ValidatableReactiveProperty(0, ignoreInitialValidationError: true); + var calls = new List(); + var registered = false; + property.SetValidateNotifyError(_ => + { + calls.Add("first"); + if (!registered) + { + registered = true; + property.SetValidateNotifyError(_ => + { + calls.Add("second"); + return (string?)null; + }); + } + + return (string?)null; + }); + + property.ForceValidate(); + calls.Is("first"); + calls.Clear(); + property.ForceValidate(); + calls.Is("first", "second"); + } + + [TestMethod] + public void ReentrantValidationPreservesErrorNotificationOrder() + { + var invalid = false; + using var property = new ValidatableReactiveProperty() + .SetValidateNotifyError(_ => invalid ? "error" : null); + var notifications = new List(); + using var subscription = property.ObserveErrorChanged.Subscribe(errors => + { + notifications.Add(string.Join(",", errors)); + if (invalid) + { + invalid = false; + property.ForceValidate(); + } + }); + notifications.Clear(); + + invalid = true; + property.ForceValidate(); + + notifications.Is("error", ""); + property.GetErrors().Is(); + } + + [TestMethod] + public void RevalidationRestoresMutatedObservedErrors() + { + using var property = new ValidatableReactiveProperty() + .SetValidateNotifyError(_ => "error"); + IReadOnlyList? observed = null; + using var subscription = property.ObserveErrorChanged.Subscribe(errors => observed = errors); + ((string[])observed!)[0] = "changed"; + + property.ForceValidate(); + + property.GetErrors().Is("error"); + } + [TestMethod] public void ValidatableReactivePropertyAggregatesMultipleErrors() { @@ -49,6 +141,124 @@ public void ValidatableReactivePropertyAggregatesMultipleErrors() changedCount.Is(2); } + [TestMethod] + public void RevalidatingUnchangedErrorsRunsValidatorsWithoutRepeatingNotifications() + { + var validatorOrder = new List(); + using var property = new ValidatableReactiveProperty(0) + .SetValidateNotifyError(_ => + { + validatorOrder.Add("first"); + return new[] { "first", "detail" }; + }) + .SetValidateNotifyError(_ => + { + validatorOrder.Add("second"); + return "second"; + }); + var errors = new List>(); + var errorsChangedCount = 0; + var propertyChangedNames = new List(); + + using var d1 = property.ObserveErrorChanged.Subscribe(x => errors.Add([.. x])); + property.ErrorsChanged += (_, _) => errorsChangedCount++; + property.PropertyChanged += (_, e) => propertyChangedNames.Add(e.PropertyName); + errors.Clear(); + validatorOrder.Clear(); + + property.ForceValidate(); + + validatorOrder.Is("first", "second"); + errors.Count.Is(0); + errorsChangedCount.Is(0); + propertyChangedNames.Count.Is(0); + property.GetErrors().Is("first", "detail", "second"); + } + + [TestMethod] + public void ChangedErrorsRetainAggregationAndNotificationOrder() + { + using var property = new ValidatableReactiveProperty(0) + .SetValidateNotifyError(x => x == 0 ? "first" : null) + .SetValidateNotifyError(x => x == 0 ? "second" : null); + var notifications = new List(); + + using var d1 = property.ObserveErrorChanged.Subscribe(x => notifications.Add($"Errors:{string.Join(",", x)}")); + using var d2 = property.ObserveHasErrors.Subscribe(x => notifications.Add($"HasErrors:{x}")); + property.ErrorsChanged += (_, _) => notifications.Add("ErrorsChanged"); + property.PropertyChanged += (_, e) => notifications.Add($"PropertyChanged:{e.PropertyName}"); + notifications.Clear(); + + property.Value = 1; + + notifications.Is( + "Errors:second", + "ErrorsChanged", + "PropertyChanged:ErrorMessage", + "Errors:", + "HasErrors:False", + "ErrorsChanged", + "PropertyChanged:ErrorMessage", + "PropertyChanged:HasErrors", + "PropertyChanged:Value"); + property.GetErrors().Is(); + } + + [TestMethod] + public void RevalidatingStreamErrorsDoesNotRepeatNotifications() + { + using var property = new ValidatableReactiveProperty(-1) + .SetValidateNotifyError(values => values.Select(x => x < 0 ? (IEnumerable?)new[] { "negative" } : null)); + var errorsChangedCount = 0; + property.ErrorsChanged += (_, _) => errorsChangedCount++; + + property.Value = -2; + + property.GetErrors().Is("negative"); + errorsChangedCount.Is(0); + } + + [TestMethod] + public void RevalidatingAsyncErrorsDoesNotRepeatNotifications() + { + var validateCount = 0; + using var property = new ValidatableReactiveProperty(0) + .SetValidateNotifyError(_ => + { + validateCount++; + return Task.FromResult("async error"); + }); + var errorsChangedCount = 0; + property.ErrorsChanged += (_, _) => errorsChangedCount++; + var initialValidateCount = validateCount; + + property.ForceValidate(); + + validateCount.Is(initialValidateCount + 1); + property.GetErrors().Is("async error"); + errorsChangedCount.Is(0); + } + + [TestMethod] + public void RevalidatingEnumerableErrorsEnumeratesInputOnce() + { + var enumerationCount = 0; + using var property = new ValidatableReactiveProperty(0) + .SetValidateNotifyError(_ => GetErrors()); + var initialEnumerationCount = enumerationCount; + + property.ForceValidate(); + + enumerationCount.Is(initialEnumerationCount + 1); + property.GetErrors().Is("error"); + + IEnumerable GetErrors() + { + enumerationCount++; + yield return "error"; + } + } + [TestMethod] public void StreamValidationUpdatesErrorStreams() { @@ -157,6 +367,29 @@ public void ValidatableReactivePropertySkipsValidationOnEqualValue() valueChangedCount.Is(0); } + [TestMethod] + public void ValidatableReactivePropertyReusesFixedPropertyChangedEventArgs() + { + using var property = new ValidatableReactiveProperty("ok") + .SetValidateNotifyError(x => x == "ng" ? "error" : null); + var propertyChangedEvents = new List(); + property.PropertyChanged += (_, e) => propertyChangedEvents.Add(e); + + property.Value = "ng"; + property.Value = "ok"; + + propertyChangedEvents.Select(static x => x.PropertyName).Is( + nameof(ValidatableReactiveProperty.ErrorMessage), + nameof(ValidatableReactiveProperty.HasErrors), + nameof(ValidatableReactiveProperty.Value), + nameof(ValidatableReactiveProperty.ErrorMessage), + nameof(ValidatableReactiveProperty.HasErrors), + nameof(ValidatableReactiveProperty.Value)); + Assert.AreSame(propertyChangedEvents[0], propertyChangedEvents[3]); + Assert.AreSame(propertyChangedEvents[1], propertyChangedEvents[4]); + Assert.AreSame(propertyChangedEvents[2], propertyChangedEvents[5]); + } + [TestMethod] public void ObserveErrorChangedIncludesEntityLevelNotifications() { diff --git a/dev-docs/adr/0009-property-path-accessor-adapters.md b/dev-docs/adr/0009-property-path-accessor-adapters.md new file mode 100644 index 00000000..6cf7956f --- /dev/null +++ b/dev-docs/adr/0009-property-path-accessor-adapters.md @@ -0,0 +1,35 @@ +# 0009. Cache property-path accessor adapters + +- **Status:** Proposed +- **Date:** 2026-11-17 +- **Deciders:** ReactiveProperty maintainers + +## Context + +Core and Legacy property paths invoke cached typed property delegates through +`DynamicInvoke`, allocating argument arrays on repeated reads and writes. These +paths also rely on reflection's argument handling and target-exception wrapping. + +## Decision + +Cache object-based getter and setter adapters per existing accessor delegate. +For compatible, non-null arguments, adapters invoke the typed delegate directly +and wrap target exceptions in `TargetInvocationException`. For other arguments, +use `DynamicInvoke` to preserve its conversions and failures. Both path +implementations share the adapters; public and protected APIs stay unchanged. + +### Alternatives considered + +- **Continue using `DynamicInvoke`** — preserves behavior but retains repeated + reflection invocation and allocations. +- **Change accessor APIs to expose object delegates** — would affect existing + extension points and require a wider compatibility change. + +## Consequences + +Steady-state invocations avoid reflection argument arrays for compatible values, +at the cost of compiling an adapter the first time each accessor is used. +The weak-key cache is thread-safe, although concurrent first use can compile +more than one adapter. Existing property discovery and expression compilation +already rely on reflection and dynamic code; trimming and Native AOT have not +been validated for this change. diff --git a/dev-docs/adr/0010-r3-validator-snapshots.md b/dev-docs/adr/0010-r3-validator-snapshots.md new file mode 100644 index 00000000..786b2005 --- /dev/null +++ b/dev-docs/adr/0010-r3-validator-snapshots.md @@ -0,0 +1,36 @@ +# 0010. Reuse R3 validator snapshots + +- **Status:** Proposed +- **Date:** 2026-11-17 +- **Deciders:** ReactiveProperty maintainers + +## Context + +Each R3 validation currently copies the registered synchronous validators and +rebuilds the aggregated errors even when a validator returns the same errors. +Registration is less frequent than validation, and validators may register +additional validators or initiate validation recursively. + +## Decision + +Replace the validator array when registering a synchronous validator, and capture +the current array under the existing validation lock before invoking validators. +Keep each snapshot immutable and preserve registration and invocation order. +Skip aggregation only when the newly materialized errors for a slot equal its +previous errors and the published aggregate still matches all slots. Observers +can retain the underlying array, so it must also be checked for mutation. +Validators and their returned sequences are still executed. + +### Alternatives considered + +- Copy the validator list on every validation: simpler registration, but repeated + allocations on the validation path. +- Read the snapshot without the lock: avoids lock acquisition but changes the + synchronization point with concurrent registration. + +## Consequences + +- Validation with unchanged errors avoids repeated snapshot and aggregation work. +- Registration copies the existing validator array and therefore costs more as the + number of validators increases. +- Sync, async and stream validation retain the existing slot and notification order. diff --git a/dev-docs/adr/README.md b/dev-docs/adr/README.md index ddea2755..9cdece68 100644 --- a/dev-docs/adr/README.md +++ b/dev-docs/adr/README.md @@ -32,6 +32,8 @@ Trivial, easily reversible choices (local refactors, naming) do not need an ADR. ## Index +Proposed follow-up: [0009. Cache property-path accessor adapters](./0009-property-path-accessor-adapters.md). + | ADR | Title | Status | |-----|-------|--------| | [0001](./0001-adopt-tdd-adr-and-dev-docs.md) | Adopt TDD, ADRs, and a dev-docs location | Accepted | @@ -42,3 +44,4 @@ Trivial, easily reversible choices (local refactors, naming) do not need an ADR. | [0006](./0006-upgrade-system-reactive-v7.md) | Upgrade the System.Reactive dependency to v7 | Accepted | | [0007](./0007-support-dotnet11-and-retire-dotnet8-and-dotnet9-targets.md) | Support .NET 11 and retire .NET 8 and .NET 9 target legs | Accepted | | [0008](./0008-remove-uwp-and-xamarin-support.md) | Remove UWP and Xamarin support from the maintained repository | Accepted | +| [0010](./0010-r3-validator-snapshots.md) | Reuse R3 validator snapshots | Proposed |