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.
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:
Post a Comment