1
0
mirror of https://github.com/chylex/.NET-Community-Toolkit.git synced 2024-11-25 10:42:45 +01:00
Commit Graph

1970 Commits

Author SHA1 Message Date
Rosario Pulella
51a28969e2 Merge branch 'master' into bugfix/totypestring-extension 2020-10-02 12:13:27 -04:00
Sergio Pedri
e91ed46bb8 Code refactoring to WeakReferenceMessenger 2020-10-01 19:15:05 +02:00
Sergio Pedri
056b414853 Code refactoring to StrongReferenceMessenger 2020-10-01 19:14:58 +02:00
Sergio Pedri
28a6e70fbb Fixed position of disabled warnings 2020-10-01 17:14:16 +02:00
Sergio Pedri
17a2cb5675 Fixed incorrect uppercase for Guard APIs 2020-10-01 17:11:25 +02:00
Sergio Pedri
8e84c62f43 Code refactoring to WeakReferenceMessenger 2020-10-01 14:53:17 +02:00
Sergio Pedri
c12516c9c4 Removed unsafe indexing from StrongReferenceMessenger 2020-10-01 13:48:04 +02:00
Michael Hawker MSFT (XAML Llama)
1783908748 Merge branch 'master' into feature/string-pool 2020-09-28 11:06:53 -07:00
Sergio Pedri
0e5cd54770 Added missing generic argument constraint 2020-09-27 15:38:40 +02:00
Sergio Pedri
be4bc38b15 Fixed two missing XML docs 2020-09-27 15:28:16 +02:00
Sergio Pedri
790ebdaab7 Merge branch 'master' into feature/array-extensions-deprecation 2020-09-26 19:40:57 +02:00
msftbot[bot]
3a581619e0 Memory usage improvements/optimizations to Messenger (#3424)
## Follow up for #3230, part of #3428 
<!-- Add the relevant issue number after the "#" mentioned above (for ex: Fixes #1234) which will automatically close the issue once the PR is merged. -->

<!-- Add a brief overview here of the feature/bug & fix. -->

## PR Type
What kind of change does this PR introduce?
<!-- Please uncomment one or more that apply to this PR. -->

- Optimization
<!-- - Bugfix -->
<!-- - Feature -->
<!-- - Code style update (formatting) -->
<!-- - Refactoring (no functional changes, no api changes) -->
<!-- - Build or CI related changes -->
<!-- - Documentation content changes -->
<!-- - Sample app changes -->
<!-- - Other... Please describe: -->

## Overview

This PR includes two main parts: an improvement for the memory pooling buffers, and a refactor of how delegates are registered for message handlers. This last part allows to completely remove local closures for message handlers 🚀

### Memory pooling improvements

We're using memory pooling (by relying on the `ArrayPool<T>` APIs) in the `Messenger` class to achieve an amortized 0-allocation execution of the `Send` method in particular (`UnregisterAll` uses this too). We have code like this:

4890b5ed17/Microsoft.Toolkit.Mvvm/Messaging/Messenger.cs (L250)

4890b5ed17/Microsoft.Toolkit.Mvvm/Messaging/Messenger.cs (L401)

This works just fine, and we do get the 0-allocation after the initial first invocation where we rent the buffer.
There are two downsides here though:
- In the `Send` method, we rent an `Action<TMessage>` buffer, so we'll rent a different buffer for every message type
- Given that these types are either internal or not likely to ever by used by consumers of the library, all these rented buffers would only ever by used by the `Messenger` class itself, and the consumers would not be able to reuse them on their own.

Neither of these points is a big deal and the current implementation is fine, but I think we can do better 😄

**Idea:** let's leverage the fact that arrays are covariant, and only use a single type to solve both problems, like so:

```csharp
object[] maps = ArrayPool<object>.Shared.Rent(count);

// Do stuff, example:
foreach (object obj in maps)
{
    var myActualItem = (SomeFancyTypePossiblyInternal)obj;

    // Do stuff with the item...
}
```

This both allows us to just use `object[]` arrays, which both reduces the total number of rented arrays (as we can reuse them for different message types), and also makes it so that these rented arrays might potentially also be reused by consumers of the library (should they ever need to pool `object[]` arrays), further reducing allocations 🚀

## Benchmarks

Here are some benchmarks comparing the `Messenger` from this PR with the one in the `Preview1`.

### Sending messages

|   Method |       Categories |         Mean |     Error |    StdDev | Ratio | Gen 0 | Gen 1 | Allocated |
|--------- |----------------- |-------------:|----------:|----------:|------:|------:|------:|----------:|
| Old_Send |   DefaultChannel |     161.7 us |   1.52 us |   1.43 us |  1.00 |     - |     - |         - |
| **New_Send** |   DefaultChannel |     **153.9 us** |   1.62 us |   1.43 us |  0.95 |     - |     - |         - |
|          |                  |              |           |           |       |       |       |           |
| Old_Send | MultipleChannels | 148,668.7 us | 886.65 us | 785.99 us |  1.00 |     - |     - |     336 B |
| **New_Send** | MultipleChannels | **138,825.0 us** | 797.61 us | 746.08 us |  0.93 |     - |     - |     336 B |

Performance when sending message is slightly faster than before. Worst case scenario, it's not any slower.

### Registering messages

|       Method |     Mean |   Error |  StdDev | Ratio |    Gen 0 |   Gen 1 | Allocated |
|------------- |---------:|--------:|--------:|------:|---------:|--------:|----------:|
| Old_Register | 443.6 us | 1.73 us | 1.53 us |  1.00 | 113.7695 | 25.3906 | 581.53 KB |
| **New_Register** | **386.1 us** | 2.47 us | 2.31 us |  0.87 |  82.5195 |  4.3945 | **381.53 KB** |

The new version is **13%** faster when registering messages, and uses **34%** less memory 🚀

### Enabled recipient type-specific handlers

One major annoyance for users working with manually registered handlers was the fact that type information was lost.
As in, recipients were registered as just `object` instances, as it was necessary to cast them in the handler every time.
This PR also changes this by adding support for a type parameter to specify the recipient type.
This enables the following change (which is totally optional anyway, you can still just use `object` if you want):

```csharp
// Before
Messenger.Register<MyMessage>(this, (s, m) => ((MyViewModel)s).SomeMethod(m));

// After
Messenger.Register<MyViewModel, MyMessage>(this, (s, m) => s.SomeMethod(m));
```

### Removed local closures

The original implementation used `Action<T>` for handlers, which caused closures to be constantly created whenever the users wanted to access any local member on the registered recipient. This was because the recipient itself needed to be captured too to be accessed from the handlers. This detail also made it more difficult for other devs to implement `IMessenger` if they wanted to use a weak reference system. I've replaced that handler type with a custom delegate, called `MessageHandler`:

204ee41ad2/Microsoft.Toolkit.Mvvm/Messaging/IMessenger.cs (L10-L22)

This delegate also receives the target recipient as input, which allows developers to just use that to access local members, without the need to create closures. The handlers are now essentially static, so the C# compiler can cache the whole delegate too. This is especially useful for the `IRecipient<TMessage>` pattern, as that was previously creating unnecessary closures when registering handlers - that's completely gone now and delegates are cached there as well 🎉

For instance, you can see that here:

204ee41ad2/Microsoft.Toolkit.Mvvm/Messaging/IMessengerExtensions.cs (L175-L179)

We're now using that cached static delegate (will be able to also explicitly mark that as static when C# 9 lands, but it already is) instead of the method group syntax on `recipient.Receive`, which allocated a closure for each invocation.

## PR Checklist

Please check if your PR fulfills the following requirements:

- [X] Tested code with current [supported SDKs](../readme.md#supported)
- [ ] ~~Pull Request has been submitted to the documentation repository [instructions](..\contributing.md#docs). Link: <!-- docs PR link -->~~
- [ ] ~~Sample in sample app has been added / updated (for bug fixes / features)~~
    - [ ] ~~Icon has been created (if new sample) following the [Thumbnail Style Guide and templates](https://github.com/windows-toolkit/WindowsCommunityToolkit-design-assets)~~
- [X] Tests for the changes have been added (for bug fixes / features) (if applicable)
- [X] Header has been added to all new source files (run *build/UpdateHeaders.bat*)
- [X] Contains **NO** breaking changes
2020-09-25 19:35:57 +00:00
Sergio Pedri
0999a1d4a9 Merge branch 'master' into optimization/messenger-shared-pool 2020-09-25 21:00:35 +02:00
Sergio Pedri
4c32abacc4 Merge branch 'master' into optimization/movsxd-removal 2020-09-24 19:56:08 +02:00
Sergio Pedri
2ff3dd5207 Merge branch 'master' into performance/generic-memory-stream 2020-09-24 19:54:43 +02:00
msftbot[bot]
0a6b93b91c HighPerformance package improvements (#3351)
## Improvements for `Microsoft.Toolkit.HighPerformance`

<!-- Add a brief overview here of the feature/bug & fix. -->

## PR Type
What kind of change does this PR introduce?
<!-- Please uncomment one or more that apply to this PR. -->

<!-- - Bugfix -->
 - Feature
 - Optimization
<!-- - Code style update (formatting) -->
<!-- - Refactoring (no functional changes, no api changes) -->
<!-- - Build or CI related changes -->
<!-- - Documentation content changes -->
<!-- - Sample app changes -->
<!-- - Other... Please describe: -->

## Changes and fixes
<!-- Describe how was this issue resolved or changed? -->

- Improved codegen for exception throw methods
- Added custom `ArrayPool<T>` overloads to `MemoryOwner<T>`

## PR Checklist

Please check if your PR fulfills the following requirements:

- [X] Tested code with current [supported SDKs](../readme.md#supported)
- [ ] ~~Pull Request has been submitted to the documentation repository [instructions](..\contributing.md#docs). Link: <!-- docs PR link -->~~
- [ ] ~~Sample in sample app has been added / updated (for bug fixes / features)~~
    - [ ] ~~Icon has been created (if new sample) following the [Thumbnail Style Guide and templates](https://github.com/windows-toolkit/WindowsCommunityToolkit-design-assets)~~
- [ ] Tests for the changes have been added (for bug fixes / features) (if applicable)
- [X] Header has been added to all new source files (run *build/UpdateHeaders.bat*)
- [X] Contains **NO** breaking changes

<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. 
     Please note that breaking changes are likely to be rejected. -->
2020-09-24 17:29:21 +00:00
Sergio Pedri
de4c07ae37 Merge branch 'master' into improvement/high-performance-tweaks 2020-09-24 18:52:51 +02:00
Sergio Pedri
f0b5215d09 Merge remote-tracking branch 'upstream/master' into optimization/messenger-shared-pool 2020-09-24 13:31:30 +02:00
Sergio Pedri
3b2d78b4a3 Merge pull request #3429 from Sergio0694/feature/mvvm-preview2
[Feature] Microsoft.Toolkit.Mvvm package (Preview 2)
2020-09-24 13:22:21 +02:00
Sergio Pedri
305e37fd03 Code refactoring (not a fan of StyleCop here) 2020-09-24 12:15:37 +02:00
Sergio Pedri
cc14122cd4 Fixed build error due to StyleCop 2020-09-24 12:10:49 +02:00
Sergio Pedri
c7a9157c35 Merge branch 'master' into feature/mvvm-preview2 2020-09-24 11:46:05 +02:00
Sergio Pedri
a1ac17dd6a Removed tracking field for HasErrors 2020-09-24 11:45:04 +02:00
Sergio Pedri
f7bc644b70 Code refactoring in ObservableValidator 2020-09-24 11:37:40 +02:00
Rosario Pulella
0aa8a19052 Merge branch 'master' into improvement/high-performance-tweaks 2020-09-23 16:00:30 -04:00
msftbot[bot]
ff29d52998 New BitHelper APIs (#3362)
## PR Type
What kind of change does this PR introduce?
<!-- Please uncomment one or more that apply to this PR. -->

<!-- - Bugfix -->
 - Feature
<!-- - Code style update (formatting) -->
<!-- - Refactoring (no functional changes, no api changes) -->
<!-- - Build or CI related changes -->
<!-- - Documentation content changes -->
<!-- - Sample app changes -->
<!-- - Other... Please describe: -->


## What is the new behavior?
<!-- Describe how was this issue resolved or changed? -->
This PR adds a few new APIs to the `BitHelper` class.
Follow up from this original thread on Twitter: https://twitter.com/SergioPedri/status/1275556765363568641.

These are the new APIs being included in this PR:

```csharp
namespace Microsoft.Toolkit.HighPerformance.Helpers
{
    public static class BitHelper
    {
        public static bool HasZeroByte(uint value);
        public static bool HasZeroByte(ulong value);
        public static bool HasByteEqualTo(uint value, byte target);
        public static bool HasByteEqualTo(ulong value, byte target);
    }
}
```

## PR Checklist

Please check if your PR fulfills the following requirements:

- [X] Tested code with current [supported SDKs](../readme.md#supported)
- [ ] ~~Pull Request has been submitted to the documentation repository [instructions](..\contributing.md#docs). Link: <!-- docs PR link -->~~
- [ ] ~~Sample in sample app has been added / updated (for bug fixes / features)~~
    - [ ] ~~Icon has been created (if new sample) following the [Thumbnail Style Guide and templates](https://github.com/windows-toolkit/WindowsCommunityToolkit-design-assets)~~
- [X] Tests for the changes have been added (for bug fixes / features) (if applicable)
- [X] Header has been added to all new source files (run *build/UpdateHeaders.bat*)
- [X] Contains **NO** breaking changes

<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. 
     Please note that breaking changes are likely to be rejected. -->
2020-09-22 16:24:21 +00:00
Michael Hawker MSFT (XAML Llama)
1452bbd151 Merge branch 'master' into feature/new-bithelper-apis 2020-09-21 14:09:27 -07:00
Sergio Pedri
204ee41ad2 Minor memory usage improvement 2020-09-20 18:17:14 +02:00
Sergio Pedri
0077e35ad9 Switched a Span<T>.CopyTo to Array.Copy 2020-09-18 23:48:31 +02:00
Sergio Pedri
6e8187536d Code tweaks to MemoryStream initialization 2020-09-18 21:59:53 +02:00
h82258652
7924645371 Merge pull request #18 from windows-toolkit/master
merge original source
2020-09-18 11:00:42 +08:00
Sergio Pedri
74474856c4 Fixed incorrect XML docs 2020-09-17 15:51:59 +02:00
Sergio Pedri
3503ca00d7 Added #ifdef block for unneeded using directive 2020-09-17 14:34:07 +02:00
Sergio Pedri
1dd75babfb Removed unnecessary constructor parameter 2020-09-17 01:20:35 +02:00
Sergio Pedri
f51ae95ce4 Added missing XML comments 2020-09-16 23:19:33 +02:00
Sergio Pedri
6f4b7bd214 Renamed file to match class name 2020-09-16 23:14:11 +02:00
Michael Hawker MSFT (XAML Llama)
aef42fd6e0 Merge branch 'master' into feature/array-extensions-deprecation 2020-09-16 13:23:54 -07:00
Sergio Pedri
fadd2bcae2 Fixed potential access violation with faulty MemoryManager<T>-s 2020-09-16 02:25:08 +02:00
Sergio Pedri
064e8d6236 Added missing file headers 2020-09-16 02:24:51 +02:00
Sergio Pedri
dc100198ce Fixed inverted readonly setting for MemoryStream 2020-09-16 02:24:36 +02:00
Sergio Pedri
a9ebf20524 Added empty stream as fallback path 2020-09-16 02:24:22 +02:00
Sergio Pedri
d72f59b79b Switched MemoryStream to generic type 2020-09-16 02:24:02 +02:00
Sergio Pedri
4b03a4e2d2 Added T[] and MemoryManager<T> owner types 2020-09-16 02:23:38 +02:00
Sergio Pedri
bbaf77179f Fixed unit test (changed type after refactoring) 2020-09-15 22:08:27 +02:00
Sergio Pedri
970d74c1c9 Added missing file headers 2020-09-15 21:22:51 +02:00
Sergio Pedri
41e345c613 Merge branch 'master' into optimization/messenger-shared-pool 2020-09-15 20:30:02 +02:00
Sergio Pedri
31ba820e5e Merge branch 'master' into feature/mvvm-preview2 2020-09-15 20:29:34 +02:00
Sergio Pedri
df2d250746 Merge pull request #28 from Sergio0694/feature/weak-tracking-messenger
Weak tracking messenger
2020-09-15 20:28:44 +02:00
Sergio Pedri
deb308de0a Renamed messenger types 2020-09-15 20:28:11 +02:00
Sergio Pedri
ae41d8f217 Improved code coverage 2020-09-14 22:51:06 +02:00