h1

Writing Fast Code the easy way Part II

October 21, 2008

Writing If conditions

The way we write If conditions can dramatically affect the performance, especially if its in a loop churning out lot of data.

Check out following two sample code (the If conditions are meaningless and are just put to simulate some conditional processing)

public void IfNested()

{

int i = 0;

while (LOOPCOUNT >= i++)

{

if (i > 20)

{

if (i > 40)

{

if (i > 60)

{

}

}

}

}

}

public void IfCombined()

{

int i = 0;

while (LOOPCOUNT >= i++)

{

if (i > 20 && i > 40 && i > 60)

{

}

}

}

Out of the above two, combined condition is a winner as it benefits from conditional short circuiting optimization in .net. It’s also always a good move to put such conditions first in order which can help the runtime to skip executing unnecessary code blocks in advance.

If( CondA && CondB && CondC) is a good one if we know that CondA can be false most of the times. If CondC is the one which can be false most of the times, the if block should be written as If( CondC && CondB && CondA).


The above readings were generated with exact same code listed above and measured using DevPartner Performance expert. Its highly recommended that before applying any performance tips in your project, make sure to measure the performance yourself.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.