h1

Writing Fast Code the easy way Part III

October 21, 2008

Switch Vs If

Use of Switch instead of If whenever possible can be quite helpful, especially if its inside a loop or any code block which is executed frequently. It can give a performance boost up to 4 times !

Check out the sample skeleton code below and the performance readings for the same.

public void SwitchTest()

{

int i = 0;

while (LOOPCOUNT >= i++)

{

switch (i)

{

case 10:

break;

case 20:

break;

case 30:

break;

case 40:

break;

case 50:

break;

case 60:

break;

case 70:

break;

}

}

}

public void IfTest()

{

int i = 0;

while (LOOPCOUNT >= i++)

{

if (i == 10)

{

}

else if (i == 20)

{

}

else if (i == 30)

{

}

else if (i == 40)

{

}

else if (i == 50)

{

}

else if (i == 60)

{

}

else if (i == 70)

{

}

}

}



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.