简体   繁体   中英

C# performance question: typeof(MyClass) vs. this.GetType()

In the first example of the log4net configuration manual the author uses typeof(MyApp) to get the type of the containing class MyApp . Is there a reason not to use this.GetType() , performance-wise? Because it seems to me that this.GetType() is much safer from potential copy-paste errors when copying into another class.

typeof(Foo) is a static type lookup; essentially it occurs at compile time, so you only get the explicitly named type.

GetType() is a dynamic type lookup; it's a virtual method that gets called at runtime and will give you the exact type even if you are using polymorphism. So it's "slower", theoretically, but it's giving you something you can't get from typeof(T) . If you need one or the other for your design, the speed isn't going to be a factor.

Performance issues aside, in the provided example, GetType isn't even an option because it is an instance method; it can't be called from a field-initializer. In any case, since the intent is to initialize a static field from a static 'context', logically a this reference can't be available - so going down the static-constructor route wouldn't help with allowing GetType either.

// Can't use GetType() - the this reference is not available.
private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM