Theme Graphic
Theme Graphic

Dink's Tidbits

... these here are all pearls I tell ya! Pearls! ...
Posted on Friday, August 28, 2009 at 2:12 PM

"is" vs "GetType" vs "typeof"


Here is an answer to a question I've seen on a lot of forums:

What's the fastest way to compare objects and types?

I put together some bench tests and found that the optimal usage of these comparison methods is very conditional.

So here is what I was testing:

The GetType() method: --- The GetType method can be found on anything inheriting "object" - which is everything. This is a part of .net reflection and will return the "Type" of any object. So for example if you have a string "bla bla bla" and you as for its type using ".GetType()", you will receive a "Type" object with information about System.string.

The typeof() method: --- The typeof method can be used on actual type statements to retrieve a "Type" object. This will return the same object that a GetType method would return from an object - except you would return this off of an actual type declaration. So "typeof(string)" would return a "Type" object with information about System.string.

The "is" statement: --- The "is" statement will compare an object with a type declaration and return either true or false if the two are a match. One thing to note about this statement is that it will recursively search the object's inheritance hierarchy to find a match. An example usage of this statement would be something like - "if (myString is string) { // some code here }".

Now realistically if you are just making a comparison with an object and its type here and there - then it really doesn't matter which one you use because any one of these comparison methods alone are so fast that they are almost unmeasurable. However, it is very often the case that a coder will run into a situation where he/she will need to run this comparison over an entire collection of items - or even collections of collections of items at which the specific performance of each of these types of comparisons will make a small difference.

Let me start off by explaining the tests set up to generate my results.

I ran 2 sets of the following 8 tests.

The first pass used the following preset variables:
object x = "testString";
Type gtype = x.GetType();
Type tstr = typeof(string);
Type tint = typeof(int);


Here are the tests I ran:
// is true test
if (x is string)

// is false test
if (x is int)

// GetType true test
if (x.GetType() == tstr)

// GetType false test
if (x.GetType() == tint)

// typeof true test
if (gtype == typeof(string))

// typeof false test
if (gtype == typeof(int))

// GetType/typeof true test
if (x.GetType() == typeof(string))

// GetType/typeof false test
if (x.GetType() == typeof(int))


Each of these tests were run 1 million times each and then compared.

When comparing strings and ints I had the following results:
____________________________
Slowest result: GetType/TypeOf False at 44.205757 milliseconds.
TestName               TestResult      Comparison
Is False                36.958457       16.39%
Is True                 37.122728       16.02%
TypeOf True             39.085807       11.58%
TypeOf False            39.110268       11.52%
GetType False           42.056464       4.862%
GetType True            42.963558       2.810%
GetType/TypeOf True     44.09567        0.249%
GetType/TypeOf False    44.205757       0%


As you can see using "is" is clearly faster here - 16% faster than using a statement with both GetType and typeof in it. Which is great when working with base value classes like int, string, double, etc...

But as stated earlier the "is" statement also checks all inheritance of an object for the comparative type. So I ran these same tests again using a Form and a Button - two classes that have a decent chain of inheritance - and here are the results I got:

____________________________
Slowest result: Is False             at 46.242734 milliseconds.
TestName               TestResult     Comparison
Is True                 36.973761       20.04%
TypeOf True             39.032228       15.59%
TypeOf False            39.045021       15.56%
GetType False           41.990402       9.195%
GetType True            42.853777       7.328%
GetType/TypeOf False    44.108595       4.615%
GetType/TypeOf True     44.60409        3.543%
Is False                46.242734       0%


And this makes sense - because the "IS FALSE" test is actually the slowest! Noting that the "IsTrue" test is still the quickest. However, also note that even though the "IS FALSE" test was the slowest - it was only slower by a mere 3-4 percent under using a "GetType + typeof" statement. So what does this mean? How can I take advantage of the -potential- speed of the "is" statements and the stability of the GetType+typeof statements?

Well like I said before, you just have to think very situationally. If you are doing a filter where you are looking through a collection of objects to find a specific type - and you know that they are mostly or halfly going to be the type you are looking for then you have a perfect situation for an "is" statement. Just make sure that in your comparison that you are not looking for specific types in a collection of items that inherit from each other - you will get a whole lot of false-positives because of the "is" statement's inheritance checking. Also if you are looking through a collection that is known to contain primitives and base types - which is rather common - then you will most definately want to use an "is" statment.

Stability-wise using GetType+typeof is going to be hard to beat with "is" statements. There will be plenty of times while coding that you are testing an object against a slew of types to find out which one it is. This is obviously a case where you expect more fails than positives and may want to take advantage of the 2-3 percent performance increase in failing tests with GetType/typeof statements. Also noting that in your coding if you can get rid of either the GetType or typeof methods from your statement you will have a just-as-stable result, but a good deal faster.

Whatever solution you prefer - good luck and happy coding!
Bookmark: Submit To Digg Submit To reddit Submit To del.icio.us Bookmark With StumbleUpon Bookmark With FaceBook Bookmark With Google Bookmarks   Share: Share By Email By Email

1 comments on ""is" vs "GetType" vs "typeof""
Posted by Kmadhav on Saturday, August 29, 2009 at 4:28 AM
Image Of Author
Get type vs typeof
this blog about Get type vs typeof is really easy to understand for user.

Best Regards disk recovery software

hard drive recovery

Leave A Comment
Subject:


Comment:
   Bold Italic Underline          Code Link Image Horizontal Rule


Because you do not have or are not logged in to your Programmer's Heaven account, please enter your name.

Name:


To help prevent comment SPAM, please enter the magic code '378' in the box:




Posting Rules
Please follow these rules when posting comments on blog posts.
  • Do not post anything that is racist, hate speech or of a sexual or adult nature.
  • Do not post or link to anything that infringes copyrighted laws.
  • Posting about security or legal topics is fine so long as you are not glorifying or encouraging people to perform illegal activities.
  • Both the author of this blog and the Programmer's Heaven administrators may delete any inappropriate comments without notice at their own discretion.
 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.