views:

154

answers:

2

Which of the following code snippets performs fastest?

if(ClassTestBase is ClassTestChild1)

or

if(ClassTestBase.Type == EClassType.Child1)

Update:

Here is the full scenario:

public enum EInheritanceTree
{
    BaseClass,
    Child1,
    Child2,
    Child3
}

public class MyBaseClass
{
    public virtual EInheritanceTree MyClassType
    {
         get
         {
              return EInheritanceTree.BaseClass;
         }
    }
}

public vlasse MyChildClass1 : MyBaseClass
{
    public override EInheritanceTree MyClassType
    {
        get
        {
            return EInheritanceTree.Child1;
        }
    }
}

Consider a method that has to compare the class type to see what kind it is. Which is the best?

public bool IsChild1(MyBaseClass myClass)
{
     if(myClass is MyChildClass1)
          return true;

     return false;
}

or

public bool IsChild1(MyBaseClass myClass)
{
     if(myClass.MyClassType == EInheritanceTree.Child1)
          return true;

     return false;
}
+1  A: 

If you're worried about performance, don't wrap all this in functions. Any code that says:

if (Obj.IsChild1() ) foo;

Should just do:

if(myClass.MyClassType == EInheritanceTree.Child1) foo;

If you're worried about the performance, any notions you may have that says to hide everything behind functions needs to be revisited. Also, why don't you just use polymorphism - that's the "right" way to make subclasses act differently.

Regardless, do some timing of your own. It's the only way to be certain which is faster.

phkahler
Also, if he is worried about this kind performance then c# is probably the wrong language as you will have more overhead in a managed language then in a unmanaged one.
Mattias Jakobsson
@Mattias Jakobsson - agreed. But sometimes you're stuck with a language for other reasons.
phkahler
-1: Method calls don't necessarily cost anything, because the compiler may inline a copy of the method. You should not do this unless you have profiler data confirming that it is a problem.
Jørgen Fogh
+1  A: 

Have you thought about using a profiler to test which is more performant yourself? Visual Studio comes with a profiler.

I would be more concerned about the need to have an enum that hold inheritance information about your application.

btlog