6

Is there a performance difference at all between importing an entire namespace versus using aliasing to import only one class? If so, how much of a difference is it?


Examples:

Importing an entire namespace:

using System.Reflection;

Aliasing to import only one class:

using BindingFlags = System.Reflection.BindingFlags;
bsara
  • 7,940
  • 3
  • 29
  • 47
  • possible duplicate of [does 'using' provide any advantages?](http://stackoverflow.com/questions/3911141/does-using-provide-any-advantages) – mbeckish Jul 09 '12 at 19:02
  • 2
    An alias should cause less clutter being offered by ImpediDense, er, IntelliSense. – HABO Jul 09 '12 at 19:15

4 Answers4

14

Zero. Namespace imports are a compile-time feature and the generated IL will be exactly the same either way.

Alan
  • 6,501
  • 1
  • 28
  • 24
  • What about at runtime when the assemblies are to be loaded? Wouldn't only the classes specified be loaded and not all classes in an entire namespace? – bsara Jul 09 '12 at 19:08
  • @Brandon The performance implications are in adding the .dll as a reference to the project. Adding a `using` statement has no effect on what is or is not loaded from those dlls. – Servy Jul 09 '12 at 19:13
  • @Brandon: This is a different aspect altogether. Namespace imports are simply time savers / readability enhancements for the source code, the resulting code is exactly the same as if you had typed out things like System.Collections.Generic.List (for example). Assembly loading and type resolution aren't directly related to namespace imports. – Alan Jul 09 '12 at 19:14
  • @Alan I just want to clarify that I understand you correctly: You're saying that when compiled, the exact same code is generated...regardless of how I've imported my namespace? I.E. where I see `Exception e` in my source code, I would actual see `System.Exception e` (or some reference to that effect) regardless of aliasing or entire namespace imports in the compiled code? – bsara Jul 09 '12 at 19:24
  • @Brandon: Exactly, yes. (Also, you can use Reflector or any other IL disassembler to verify.) – Alan Jul 09 '12 at 19:28
5

No it is just an help for the programmer, the CIL generated by the compiler is exactly the same.

BlackBear
  • 22,411
  • 10
  • 48
  • 86
3

There's no performance difference. One says 'look here when I specify a class name, it might be in here'. The other says 'when I say this class or namespace, I mean use this one'.

Kieren Johnstone
  • 41,277
  • 16
  • 94
  • 144
-1

No but even more broad. You load the dll that contains the .net core and it'll have dozens of namespaces in it. You really don't take a hit for importing namespaces till you walk outside of the already loaded dll.

WhiteleyJ
  • 1,393
  • 1
  • 22
  • 29