IL Code does Not reflect C# using
Runtime Performance
Is there benefit to the USING
directives being used this way in
nested namespaces? Such as memory
management or the JIT compiler?
Because you're asking about runtime performance, here's a look into what's happening underneath the source code.
If you look at the compiled IL code with Microsoft's IL Diassembler tool (as we're doing here) you will see all class names are fully qualified all the time no matter how the programmer used using
in the source code.
In the following sample of compiled IL code notice no "shortcut" mechanism is seen although using
was in the original C# source code files. For example IL describes one long extends [System.Web]System.Web.UI.Page
whereas C# would have used : Page
and also using System.Web.UI;
(two separate statements).
// ***** Compiled MSIL CODE ****
// Notice all fully qualified classes throughout.
//
.class public auto ansi beforefieldinit WebApplication1.process
extends [System.Web]System.Web.UI.Page
{
.field family class [System.Web]System.Web.UI.HtmlControls.HtmlForm form1
.method family hidebysig instance void
Page_Load(object sender,
class [mscorlib]System.EventArgs e) cil managed
{
// Code size 95 (0x5f)
.maxstack 4
.locals init ([0] string strName,
[1] string strTime)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: call instance class [System.Web]System.Web.HttpRequest [System.Web]System.Web.UI.Page::get_Request()
IL_0007: ldstr "name"
IL_000c: callvirt instance string [System.Web]System.Web.HttpRequest::get_Item(string)
In the compiled IL all classes are fully qualified regardless.
This means there are no performance benefits or drawbacks at runtime based on the design time using
statements.
Compile Time
Depending on how you scatter about your using
s and namespace
s in the source code, there might be more or less of the keywords hanging around. The compiler has to see them all and process them all but overall the compile performance would be negligible for something this trivial, compared to all things a compiler has to do to make the finished product.
Design Time Benefits
namespaces are an organizational technique and using
is a way of managing them at the source code level (and to instruct the compiler how you're using them so it can compile the program accordingly). When C# source specifies using System.Web.UI;
, nothing is imported and the file size doesn't grow larger (because the assembly is already referenced in); instead using
is simply effecting a shorter syntax to the contents of that namespace, from within the scope the using
is used in, whether that be in the entire file scope or a declared namespace scope inside the file.
The benefit to the programmer is reduction of ambiguous class name conflicts between multiple namespace using
s if they are judiciously used.
Organization of source code namespaces is represented differently in the compiled IL code (as seen in the above example).