Why LoadLibrary is much slower than GetModuleHandle for dll that is already loaded?

This question is asked in our internal discussion list. One of the kernel developer answered the question below:


LoadLibrary(AlreadyLoadedModule) has to increment the reference count of AlreadyLoadedModule, plus all of that module's dependencies, and their dependencies, recursively.  Since the dependencies are recorded by name, not by a pointer to the loader entry, finding each dependency requires applying the isolation/redirection info in the activation context.  For a module with a lot of imports, or imports which have their own large trees, this makes a LoadLibrary call quite expensive, even if it's already loaded.

GetModuleHandle is a better alternative.


This is a FYI post. I won't answer any question.

Comments (6)

  1. RealOne says:

    GetModuleHandle is a better alternative.


  2. Jason Haley says:

    Interesting finds this week

  3. Dean Harding says:

    I wouldn’t say GetModuleHandle was a better alternative at all. At least not in general (I can’t say for the context this discussion was in). There’s a pretty major race condition where you might call GetModuleHandle but before you actually try to use the returned handle, the module is unloaded by another thread. That’s not a problem with LoadLibrary because it increments the ref count for you.

  4. Everything has to be discussed in a context.

    The context here is about performance, not about reliability.

  5. Dean Harding says:

    Right, like I said, I couldn’t speak for the context of this discussion. But I was just warning people that this is not a general solution for a faster version of LoadLibrary.

    You’d need to add extra code to make sure the libraries are never unloaded until all your GetModuleHandle callers have finished with it (for example, you’d call LoadLibrary the first time, then use GetModuleHandle subsequent times, then when you’re all done you can do a FreeLibrary).

Skip to main content