Thursday, 12 September 2013

Redundant/Better Performance Code VS Optimized/Less Performance Code

Redundant/Better Performance Code VS Optimized/Less Performance Code

In my case, I'm using C#, but the concept of the question would apply to
Java as well. Hopefully the answer would be generic enough to cover both
languages. Otherwise it's better to split the question into two.
I've always thought of which one is a better practice.
Does the compiler take care of enhancing the 'second' code so its
performance would be as good as the 'first' code?
Could it be worked around to get a 'better performance' and 'optimized'
code at the same time?
Redundant/Better Performance Code:
string name = GetName(); // returned string could be empty
List<string> myListOfStrings = GetListOfStrings();
if(string.IsNullOrWhiteSpace(name)
{
foreach(string s in myListOfStrings)
Console.WriteLine(s);
}
else
{
foreach(string s in myListOfStrings)
Console.WriteLine(s + " (Name is: " + name);
}
Optimized/Less Performance Code:
string name = GetName(); // returned string could be empty
List<string> myListOfStrings = GetListOfStrings();
foreach(string s in myListOfStrings)
Console.WriteLine(string.IsNullOrWhiteSpace(name) ? s : s + " (Name
is: " + name);
Obviously the execution time of the 'first' code is less because it
executes the condition 'string.IsNullOrWhiteSpace(name)' only once per
loop. Whereas the 'second' code (which is nicer) executes the condition on
every iteration.
Please consider a long loop execution time not a short one because I know
that when it is short, the performance won't differ.

No comments:

Post a Comment