开发者

Faster to Compare by Name or Type?

When performing an object comparison, is it faster to compare by name (string) or t开发者_开发知识库ype (pointer)?

See below:

if(sender is DataGridView) { .. }

or

if(sender.GetType().ToString() == "System.Forms.DataGridView") { .. }

Note: I may not have the syntax exactly right... this is a C# example, but the comment answer here in one my questions made me think about it.


The two aren't equivalent. The second will only be matched if the type of sender is exactly DataGridView. The first will be matched if the type is, or inherits from, DataGridView. So point one, the comparisons are not the same. As Benjamin Podszun says in his answer, the correct comparison for exact type equality is:

instance.GetType() == typeof(Class)

That aside, my gut feeling is that type comparison will be faster for sure if the type is exactly DataGridView, but that it will be less clear cut in the case where it is a descendant type.


if (sender.GetType().ToString() == "System.Forms.DataGridView")

should probably better be

if (sender.GetType() == typeof(DataGridView))

whatever the performance characteristics might be.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜