Search code examples
c#.netvb.netdlldll-reference

How expensive is a DLL reference?


Either local or global (GAC / .NET) DLL references, how expensive they are?

For sure we should never reference things we don't use, but for curiosity I ask: Would it be a big performance concern referencing the whole .NET framework?

A similar more practical question would be: Is it worth to combine similar namespaces in projects to minimize the DLL files that need to be referenced (as long as I have to use every code in those DLLs in any case)?


Solution

  • A reference is loaded only when you execute a method, which uses a type from the referenced .dll. So even if you reference the whole .NET framework, it will not be loaded automatically.

    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
            Console.WriteLine("=====Working with URI...=====");
            WorkWithUri();
    
            Console.WriteLine("=====Working with XML...=====");
            WorkWithXml();
        }
    
        private static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
        {
            Console.WriteLine(args.LoadedAssembly.FullName + " has been loaded.");
        }
    
        private static void WorkWithUri()
        {
            var uri = new Uri("c:\\");
        }
    
        private static void WorkWithXml()
        {
            XDocument xml = new XDocument();
        }
    }
    

    And the output:

    =====Working with URI...=====
    System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 has been loaded.
    =====Working with XML...=====
    System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 has been loaded.
    System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 has been loaded.
    System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 has been loaded.
    Press any key to continue . . .