dimanche 11 septembre 2016

What is faster in C#, an if statement, or a virtual function call to a function that does nothing? And why?

Say you have a class called MyClass which has a certain behavior encapsulated using a reference (myBehavior) to another class called Behavior. By default MyClass should have no behavior.

For instances which hadn't set myBehavior to anything after it was initialized - Would it be more speed efficient if myBehavior was initialized to null, and each time it was needed checked with if(myBehavior) or would it be faster if it were initialized to an instance of a NullBehavior, derived from Behavior, which does nothing? and why?

class MyClass
{
   Behavior myBehavior = null;

   void doSomething()
   {
      if(myBehavior)
      {
         myBehavior.performAction();
      }
   }
}

or:

class NullBehavior : Behavior
{
   override void performAction()
   {
      // don't do anything
   }
}

class MyClass
{
   Behavior myBehavior = new NullBehavior(); // or equals some static universal instance of NullBehavior

   void doSomething()
   {
      myBehavior.performAction();
   }
}

Aucun commentaire:

Enregistrer un commentaire