Tutorial :Is referencing a method/variable in an external namespace more memory efficient than including it entirely?


So is the following equivalent in memory usage?



using System.Threading;  ...  Thread.Sleep(500);  

I would have thought that the less namespaces you're 'using' in memory the better, but I've heard that the former example has to load the namespace into memory regardless. I know Sleep isn't the best example of a memory hungry method but it's just an example.


The using statement doesn't cause anything at all to be loaded, it only tells the compiler where to look for classes.

The two examples produces exactly the same code.


The two produce exactly the same IL when compiled, as said in the other posts.

There is a difference, though. The first option explicitly lets the compiler know where to go for the class/method/struct/etc. The second options includes the namespace (System.Threading) into the compiler's list of namespaces to search.

If you have many namespaces in using statements, it will cause the compiler to take longer to compile this file. With C#, this is probably not something you'd ever care about, since the compiler is so damn fast, but it does slow things down.

With a very large project, and very large namespaces (which isn't a good idea for other reasons), this can be noticeable (although still subtle).


I don't believe you can equivocate a "using" statement with an "include" statement in the sense of includes in plain C -- when CLR code is compiled, it will ignore specified namespaces that are not actually used in the assembly.

The using statement is for:

  • Telling the compiler where to look for classes (as stated by Guffa)
  • Making it easier for developers to declare classes -- imagine having to type in the fully qualified class name every single time on every single declaration

The compiler will be responsible for optimizing it, nothing for you to worry about.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »