-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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
Memory usage improvements/optimizations to Messenger #3424
Memory usage improvements/optimizations to Messenger #3424
Conversation
Thanks Sergio0694 for opening a Pull Request! The reviewers will test the PR and highlight if there is any conflict or changes required. If the PR is approved we will proceed to merge the pull request 🙌 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Think we could just add the extra checks there in the tests quick, but otherwise think this seems good.
Weak tracking messenger
…enger-shared-pool
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good! 🎊
Hello @Sergio0694! Because this pull request has the p.s. you can customize the way I help with merging this pull request, such as holding this pull request until a specific person approves. Simply @mention me (
|
## Follow up for #3424 <!-- 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. --> - Bugfix-ish <!-- - 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 <!-- Please describe the current behavior that you are modifying, or link to a relevant issue. --> The .NET 5 target currently uses the .NET Standard 2.0 code path within `WeakReferenceMessenger`. Not technically a bug since the implementation does work, but it can be greatly simplified like on .NET Standard 2.1. This should also make the code add slightly less GC pressure over time due to less additional data structures in use. ## 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:/windows-toolkit/WindowsCommunityToolkit-design-assets)~~ - [X] New major technical changes in the toolkit have or will be added to the [Wiki](https:/windows-toolkit/WindowsCommunityToolkit/wiki) e.g. build changes, source generators, testing infrastructure, sample creation changes, etc... - [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
Follow up for #3230, part of #3428
PR Type
What kind of change does this PR introduce?
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 theMessenger
class to achieve an amortized 0-allocation execution of theSend
method in particular (UnregisterAll
uses this too). We have code like this:https:/windows-toolkit/WindowsCommunityToolkit/blob/5bf426523cf456fc13db7b6505c56cad380d5f5f/Microsoft.Toolkit.Mvvm/Messaging/Messenger.cs#L250
https:/windows-toolkit/WindowsCommunityToolkit/blob/5bf426523cf456fc13db7b6505c56cad380d5f5f/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:
Send
method, we rent anAction<TMessage>
buffer, so we'll rent a different buffer for every message typeMessenger
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:
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 poolobject[]
arrays), further reducing allocations 🚀Benchmarks
Here are some benchmarks comparing the
Messenger
from this PR with the one in thePreview1
.Sending messages
Performance when sending message is slightly faster than before. Worst case scenario, it's not any slower.
Registering messages
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):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 implementIMessenger
if they wanted to use a weak reference system. I've replaced that handler type with a custom delegate, calledMessageHandler
:https:/windows-toolkit/WindowsCommunityToolkit/blob/32656db1cdd4ddc25e3a88c297ce4062fe64d2ad/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:
https:/windows-toolkit/WindowsCommunityToolkit/blob/32656db1cdd4ddc25e3a88c297ce4062fe64d2ad/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:
Pull Request has been submitted to the documentation repository instructions. 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