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

橙三吉。 提交于 2019-12-04 02:59:48

问题


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.


回答1:


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.




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/15392766/in-c-is-it-more-performant-to-use-fully-qualified-names-vs-the-using-directi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!