Sunday, September 7, 2008

Writing Fast Code the easy way Part III

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.

No comments: