简体   繁体   中英

Performance impact of unused “using” directives in C#

Just curious about it.

Does it matter if I add multiple using directives at the starting of my code file which I don't use in my code. Like this.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
//using blah.. blah.. blah..;

public class myClass
{
    // Class members
}
  • Does it have a bad impact on my application's memory usage ?

  • Does it have a bad impact on my application's performance ?

I know it is a good practice to remove them and we have short full support of .Net IDE to do so, but I am just curious to know about it.

Extra Using directives will not have any memory/performance impact on final application - they are nothing but compiler provided shortcuts to deal with long type names. Compiler uses these namespaces to resolve unqualified (or partly qualified) type names to correct types.

Just for the sake of completeness, the IL generated for this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Hello World!");
        }
    }
}

and this:

class Program
{
    static void Main(string[] args)
    {
        System.Console.Write("Hello World!");
    }
}

are exactly the same:

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       13 (0xd)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "Hello World!"
  IL_0006:  call       void [mscorlib]System.Console::Write(string)
  IL_000b:  nop
  IL_000c:  ret
} // end of method Program::Main

There are no performance hits on your application. It's just a shortcut you use to avoid typing the entire qualification. eg

var f = new File()

instead of

var f= new System.IO.File();

HOWEVER. it DOES impact the performance of your development environment (IDE) somewhat because the more using statements you use, the larger the auto-complete cache grows. This makes lookup times slightly slower. But this is usually hardly noticeable.

This advice doesn't apply to adding assembly references to your project though. If you add a reference to MyGloriousLibrary.DLL and never use it, you're gonna have a bad time.

It doesn't affect the overall performance or memory usage of your application at all. The using directives are just there at compile time, so that you don't have to write out the full class name every time. There is nothing left of those directives once your code is compiled (the compiled code always uses full type names).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM