In C#, is it more performant to use fully qualified names vs the 'using' directive?
Asked Answered
T

4

16

In C#, when you add a using directive for a namespace, it gives you access to all the types in that specific namespace. However, if the namespace has a lot of types and I only need one particular one, I often just use the fully qualified name thinking that I don't want to make available any unnecessary classes I know I am not going to use (especially if there are a lot of them in that namespace) for performance reasons. I was thinking that there has to be some impact to performance (no matter how minute) to make them available as opposed to not, but how much? (if there actually is one). And if so, would it then be bad practice to do this all over the place, because wouldn't it then start to accumulate to something noticable (performance wise)?

I did see the other SO post about using the using directive vs fully qualified names, but it wasn't in reference to performance.

Thurnau answered 13/3, 2013 at 17:50 Comment(2)
Adding using directives will not affect run-time performance. See #14581106Linctus
I'm not sure, maybe its only a matter of syntax sugar?Syrupy
H
29

The using directive is only syntactic sugar that disappears during compilation. Whether or not the namespace was included via using or mentioned in a fully-qualified type name is totally irrelevant in the resulting bytecode. Hence, there is no performance benefit at runtime by using one or the other.

Hawkeyed answered 13/3, 2013 at 17:53 Comment(0)
H
7

There is no difference.

It might have a negligible (i.e. probably not measurable) impact/benefit on compiler performance (as in when running msbuild), but at runtime the IL explicitly knows the type that is intended, as it's baked in the code as a type handle. There is no 'searching' for types unless reflection is being used.

Hence answered 13/3, 2013 at 17:53 Comment(1)
Minor terminology, but I'd say that it "explicitly" knows the type that is intended...Ecbolic
D
3

I must say, NO. The compiler will produce the same IL code, so you don't have to worry about that.

Dextroamphetamine answered 13/3, 2013 at 17:54 Comment(0)
M
0

that just depends.

Using the using directive helps you to write your code faster. But, if you have e.g 2 namespaces where you use the using directive which both have methods which have the same name and also have the same signature you will get into trouble.

Using the full qualified reference can make your code more understandable.

Monochrome answered 13/3, 2013 at 17:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.