Skip to content

Improve performance of Enum*Windows() interop functions - #2639

Merged
RussKie merged 2 commits into
dotnet:masterfrom
kpreisser:improveEnumWindowsPerformance
Jan 14, 2020
Merged

RussKie merged 2 commits into
dotnet:masterfrom
kpreisser:improveEnumWindowsPerformance

Conversation

@kpreisser

@kpreisser kpreisser commented Jan 6, 2020 •

Copy link
Copy Markdown
Contributor

Proposed changes

In EnumWindows, EnumChildWindows, and EnumThreadWindows, instead of passing the supplied callback delegate to the native function, use a (fixed) static delegate, and specify a handle pointer of the supplied callback in the lParam parameter (that is available for storing application-provided data).

That way, the CLR no longer needs to allocate memory for each delegate instance in order to store a native code block (that contains the closure pointer), thus improving performance in many cases (see comparison below). (On the other hand, the invoked callback delegate now has a little bit more work to do, by dereferencing a GCHandle and calling another method.)

This can especially improve speed when running x86 applications on ARM64 systems, as it avoids the need for the emulation layer to generate new ARM64 code from the x86 code every time the method is invoked with a new delegate instance.

Note: In Form.RecreateHandleCore there was a call to EnumThreadWindows where the form handle was passed as lParam data, but I think it makes more sense to store it in the callback closure since a new instance of the delegate is created anyway.

Note: I'm not sure about the naming/placement of the delegate types. In the native declarations, all functions use WNDENUMPROC as callback type.

Customer Impact

  • Better performance and reduced memory footprint in many cases when using code that calls EnumWindows, EnumChildWindows or EnumThreadWindows.
    In specific cases (when the callback is called very often), performance might be slower due to the additional work the callback has to do.

Regression?

  • No

Risk

Test methodology

Performance

  • Manual testing using a code like this (for EnumChildWindows):
    class Program
    {
        [STAThread]
        private static void Main()
        {
            var f = new Form();
            f.Controls.Add(new Button());
            f.Controls.Add(new CheckBox());
            f.Controls.Add(new RadioButton());

            var handle = f.Handle;

            f.Show();

            var sw = new Stopwatch();
            for (int i = -5; i < 100000; i++)
            {
                if (i == 0)
                    sw.Start();

                Interop.User32.EnumChildWindows(
                    handle, new EnumChildWindowsTest().HandleCallback);
            }
            sw.Stop();
            f.Close();
            f.Dispose();
            Console.WriteLine("Elapsed: " + sw.ElapsedMilliseconds);            
        }

        private class EnumChildWindowsTest
        {
            private int count;

            public Interop.BOOL HandleCallback(IntPtr hWnd)
            {
                count++;
                return Interop.BOOL.TRUE;
            }
        }
    }

Average time before/after this PR:

  • x86 app on a x64 system (Windows 10 Version 1909)
    • Before: ~660 ms
    • After: ~370 ms
    • Factor: 1.8x
  • x64 app:
    • Before: ~400 ms
    • After: ~280 ms
    • Factor: 1.4x
  • x86 app on a (slow) ARM64 machine (Windows 10 on ARM on Raspberry Pi 3 B+):
    • Before: ~27.0s
    • After: ~5.4s
    • Factor: 5.0x

Note: When the callback is called more often (e.g. about 200 times when calling EnumWindows), the timing improvement vanishes with a x64 app, probably because the callback delegate has now a bit more work to do.

Test environment(s)

.NET Core SDK (reflecting any global.json):
Version: 5.0.100-alpha1-016073
Commit: bd7bf8c6d2

Runtime Environment:
OS Name: Windows
OS Version: 10.0.18363
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\5.0.100-alpha1-016073\

Host (useful for support):
Version: 5.0.0-alpha.1.19564.1
Commit: c77948d92a

.NET Core SDKs installed:
3.1.100 [C:\Program Files\dotnet\sdk]
5.0.100-alpha1-016073 [C:\Program Files\dotnet\sdk]

Microsoft Reviewers: Open in CodeFlow

@kpreisser
kpreisser requested a review from a team as a code owner January 6, 2020 14:52
@kpreisser kpreisser changed the title Improve performance (and memory usage) of Enum*Windows() interop functions Improve performance of Enum*Windows() interop functions Jan 7, 2020
@RussKie
RussKie requested a review from JeremyKuhne January 8, 2020 00:25
@RussKie RussKie added enhancement Product code improvement that does NOT require public API changes/additions tenet-performance Improve performance, flag performance regressions across core releases waiting-review This item is waiting on review by one or more members of team labels Jan 8, 2020
JeremyKuhne
JeremyKuhne previously approved these changes Jan 13, 2020

@JeremyKuhne JeremyKuhne left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! Looks good!

@RussKie RussKie removed the waiting-review This item is waiting on review by one or more members of team label Jan 14, 2020
@RussKie

RussKie commented Jan 14, 2020

Copy link
Copy Markdown
Contributor

MC, please rebase

@RussKie RussKie added the waiting-author-feedback The team requires more information from the author label Jan 14, 2020
…tions.

This is done by passing a static delegate to the native function and supplying the callback as reference data. Otherwise, when we would supply the callback directly, the CLR would have to generate a native code block (for storing the closure pointer) for each callback delegate instance.
@kpreisser
kpreisser force-pushed the improveEnumWindowsPerformance branch from 016b7df to 6fe940e Compare January 14, 2020 18:22
@ghost ghost removed the waiting-author-feedback The team requires more information from the author label Jan 14, 2020
@codecov

codecov Bot commented Jan 14, 2020 •

Copy link
Copy Markdown

Codecov Report

Merging #2639 into master will decrease coverage by 0.56349%.
The diff coverage is 47.82609%.

@@                Coverage Diff                 @@
##              master       #2639        +/-   ##
==================================================
- Coverage   58.15075%   57.58726%   -0.5635%     
==================================================
  Files           1240        1233         -7     
  Lines         423004      417542      -5462     
  Branches       38852       38753        -99     
==================================================
- Hits          245980      240451      -5529     
- Misses        171650      171714        +64     
- Partials        5374        5377         +3
Flag Coverage Δ
#Debug 57.58726% <47.82609%> (-0.5635%) ⬇️
#production 31.36082% <47.82609%> (-0.12524%) ⬇️
#test 98.93067% <ø> (+0.00099%) ⬆️

@RussKie
RussKie merged commit 4a69ae6 into dotnet:master Jan 14, 2020
@ghost ghost added this to the 5.0 milestone Jan 14, 2020
@kpreisser
kpreisser deleted the improveEnumWindowsPerformance branch January 16, 2020 19:58
@ghost ghost locked as resolved and limited conversation to collaborators Feb 2, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

enhancement Product code improvement that does NOT require public API changes/additions tenet-performance Improve performance, flag performance regressions across core releases

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants