Micro Performance optimisation using If-Else
Posted: October 18, 2011 Filed under: C#.net | Tags: Conditional (programming), if-else, performance-optimization Leave a comment »This post is actually a question I asked on Stackoverflow,
The question is Which performs better if or if-else ?, this might seem to be a silly question for a few because of 2 reasons.
- If block will have relatively less lines of code, if both the blocks are having the same code, it is apparently a matter of commonsense.
- And if they are not having the same code then we should not compare them in the first place
The If Block
public long WithOnlyIf(int myFlag)
{
Stopwatch myTimer = new Stopwatch();
string someString = "";
myTimer.Start();
for (int i = 0; i < 1000000; i++)
{
string height = "80%";
string width = "80%";
if (myFlag == 1)
{
height = "60%";
width = "60%";
}
someString = "Height: " + height + Environment.NewLine + "Width: " + width;
}
myTimer.Stop();
File.WriteAllText("testif.txt", someString);
return myTimer.ElapsedMilliseconds;
}
The If-Else Block
public long WithIfAndElse(int myFlag)
{
Stopwatch myTimer = new Stopwatch();
string someString = "";
myTimer.Start();
for (int i = 0; i < 1000000; i++)
{
string height;
string width;
if (myFlag == 1)
{
height = "60%";
width = "60%";
}
else
{
height = "80%";
width = "80%";
}
someString = "Height: " + height + Environment.NewLine + "Width: " + width;
}
myTimer.Stop();
File.WriteAllText("testifelse.txt", someString);
return myTimer.ElapsedMilliseconds;
}
So Which one actually performs better, well lets look into the results
When Condition is true, the If Block took 1700 milliseconds to execute the 1000000 iterations, where as the if-else block took only 1688 milliseconds
When the conditions fails, the if scored 1677 Milliseconds which is still a bit late than the If-Else block’s 1664 Milliseconds
So the results say that If-Else performs better than If and guess according to most of SO posters the If-Else block is more readable too
Advertisement

