Note that there are some explanatory texts on larger screens.

plurals
  1. PORedundant/Better Performance Code VS Optimized/Less Performance Code
    text
    copied!<p>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.</p> <p>I've always thought of which one is a better practice.</p> <p>Does the compiler take care of enhancing the 'second' code so its performance would be as good as the 'first' code?</p> <p>Could it be worked around to get a 'better performance' <strong>and</strong> 'optimized' code at the same time?</p> <p><strong>Redundant/Better Performance Code:</strong></p> <pre><code>string name = GetName(); // returned string could be empty List&lt;string&gt; 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); } </code></pre> <p><strong>Optimized/Less Performance Code:</strong></p> <pre><code>string name = GetName(); // returned string could be empty List&lt;string&gt; myListOfStrings = GetListOfStrings(); foreach(string s in myListOfStrings) Console.WriteLine(string.IsNullOrWhiteSpace(name) ? s : s + " (Name is: " + name); </code></pre> <p>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.</p> <p>Please consider a long loop execution time not a short one because I know that when it is short, the performance won't differ.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload