Often I see questions on how to speed up a particular algorithm, to which I see the answers:

"Using WinAPI allows you to speed up the algorithm."

Is it fair?

After all, all .NET methods are a convenient wrapper over WinAPI and, in my opinion, to whom, if not microsoft, you can see how to get the maximum performance from your api?

Actually it makes me doubt.

  • five
    to find out which horse is faster, you need to arrange horse racing - Grundy
  • one
    "all .NET methods are a convenient wrapper over WinAPI" and probably not casual. - Valera Kvip
  • one
    For convenience, performance could be sacrificed. - Alexander Petrov
  • @AlexanderPetrov, I agree, however, I do not believe that you can get something faster more than 10-20%. - iluxa1810

2 answers 2

WinAPI - unmanaged code. Unmanaged code is faster than managed code. But there is one very important BUT - unmanaged code runs faster than managed, if and only if used correctly and as intended .

.NET does provide a lot of convenient wrappers for native WinAPI code and more. These wrappers partly allow you to get rid of the need to write a lot of verification when using your hands and lower the entry threshold for novice programmers, as well as reduce the amount of work for experienced programmers, where there is no need to squeeze 100% of the performance from iron. In assembly language, you can write a program that squeezes everything out of iron to the last drop, but this will require significantly higher developer qualifications, development time and project budget, so usually below the C / C ++ level do not even go down where you need maximum performance.

Therefore, before changing the calls of the .NET classes to the WinAPI calls, it is worth going through the profiler on the problematic code and find out what decreases the performance. In most cases, it turns out that the problem does not concern WinAPI or wrapping classes at all. Moreover, if you take into account the very modest documentation on WinAPI, then without having serious experience with it, you rather get an even greater drawdown in performance, a dozen incomprehensible bugs and, as a result, a lot of extra time for all this ugliness, as they often say - " shoot yourself in the leg. "

First, you need to squeeze the most out of the architecture and algorithms of the program, and then, if this is not enough, look towards replacing the managed code with the unmanaged one.

Of course, all this does not concern projects and programmers initially working with unmanaged code.

    No, this is not always fair.

    A canonical counterexample is the class ManualResetEventSlim , which in normal use is faster by an order of magnitude than a direct wrapper to the WinAPI-event ManualResetEvent .

    (The difference is that ManualResetEventSlim several wait cycles before transferring control to the kernel. During this wait, it is likely to end, so in this case the gain is evident.)