Witch one of this approaches you think is better ?
This example is in PHP but the rules of the game are the same for other languages.
1. First make a single if block and duplicate the template string in the else block:
if($var['b'])
{
$text='<tr>
<td style="cursor:pointer; color:black;"></td>
<td class="one">'.$var['b'].'</td>
<td class="two">'.$var['b'].'/'.$var['a'].'</td>
<td class="other">'.($var['a']/$var['b']).'</td>
</tr>';
} else {
$text='<tr>
<td style="color:red;"></td>
<td class="one"></td>
<td class="two">'.$var['a'].'</td>
<td class="other">0</td>
</tr>';
}
2. Second check the same variable over and over again but don’t duplicate the template string:
$text='<tr>
<td style="'.(($var['b'])?'cursor:pointer; color:black;':'color:red;').'"></td>
<td class="one">'.(($var['b'])?$var['b']:'').'</td>
<td class="two">'.(($var['b'])?$var['b'].'/'.$var['a']:$var['a']).'</td>
<td class="other">'.(($var['b'])?($var['a']/$var['b']):'0').'</td>
</tr>';
3. Third a single variable check, don’t duplicate the template string, set / unset variables:
$css = 'color:red;';
$one = '';
$two = $var['a'];
$other = 0;
if($var['b'])
{
$css = 'cursor:pointer; color:black;';
$one = $var['b'];
$two = $var['b'].'/'.$var['a'];
$other = ($var['a']/$var['b']);
}
$text='<tr>
<td style="'.$CSS.'"></td>
<td class="one">'.$one.'</td>
<td class="two">'.$two.'</td>
<td class="other">'.$other.'</td>
</tr>';
unset($css,$one,$two,$other);
This is a simple example, so doesn’t matter, but imagine a big project where something like this can be used ten to hundred of times just for a single script instance. In the first we have a bigger source code, but we gain speed, in the second our code is small (allmost hard to read), but we loose some speed beacause of multiple variable checks, the third is easy to read, don’t use much space, but we loose some speed and memory beacause of setting and unseting of variables.
I have learn one thing related to this question browsing SO in the latest months:
Readability of the code is important, so doesn’t mather what approach do you use, as long as your code is easy to read by humans, beacause modern compilers do their job very well in optimizing your code in the way it run as faster as it can.