nsfnotthrowingaway nsfnotthrowingaway - 2 months ago 8
C# Question

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();
}
}

Answer

Let's imagine what will happen with ASM code (after IL):

  • wrapping it with if will generate extra mov + cmp + jnz instructions.

  • calling function will execute call and ret calls which affect callstack maintenance (saving and restoring). It will probably generate something like: call ... then push ebp mov ebp, esp ... pop ebp retto save it and then extra code to restore it.

Obviously calling function consume more CPU operations comparing to if. But on other hand if your call function will be called each time (i.e. myBehavior is typically set) then we are wasting extra operation on jnz/if.

So if you can predict that myBehaviour will be most likely set (not null / NullBehavior) then you should go with second option without extra if but if it's more likely to be null then it worth wrapping it with if.

Comments