tags:

views:

117

answers:

3

When performing an object comparison, is it faster to compare by name (string) or type (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.

+10  A: 

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.

David M
+2  A: 
if (sender.GetType().ToString() == "System.Forms.DataGridView")

should probably better be

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

whatever the performance characteristics might be.

Benjamin Podszun
+1  A: 

I'm almost sure this:

sender.GetType() == typeof(DataGridView)

will be faster than this:

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

If you compare two strings, you need to compare many characters. This might take linear time. If you compare two Type objects, it's probably enough to test for reference equality. This could be done in constant time.

I'm not sure if the above statement is 100% correct, but I'm fairly confident that it's not a good idea, and also not efficient, to compare types by their string representations.

stakx