I doubt that it makes a “huge” impact on performance, but I was wondering if PHP Loops are better optimized than spitting out HTML with PHP variables instead?
A very simple example would be something like this:
which is “more efficient”:
<?php
$i = 0;
$settings = array(
1 => 'var_a|var_one',
2 => 'var_b|var_two',
3 => 'var_c|var_two',
4 => 'var_d|var_three',
);
foreach($settings as $setting) {
$e = explode('|', $setting);
if(get_option($e[0]) !== ''){ ?>
<li class="radio">
<h2><?php print($e[1]); ?></h2>
<input name="radio_ask" type="radio" value="<?php print($e[0]); ?>" id="radio_<?php print($i); ?>" tabindex="<?php print($i); ?>" onclick="this.setAttribute('checked', 'checked'); this.checked = true;">
</li>
<?php }
}
?>
or
<?php
if(get_option('var_a') !== ''){ ?>
<li class="radio">
<h2><?php print( get_option('var_one')); ?></h2>
<input name="radio_ask" type="radio" value="<?php print( get_option('var_a')); ?>" id="radio_1" tabindex="1" onclick="this.setAttribute('checked', 'checked'); this.checked = true;">
</li>
}
if(get_option('var_b') !== ''){ ?>
<li class="radio">
<h2><?php print( get_option('var_two')); ?></h2>
<input name="radio_ask" type="radio" value="<?php print( get_option('var_b')); ?>" id="radio_2" tabindex="2" onclick="this.setAttribute('checked', 'checked'); this.checked = true;">
</li>
<?php } ?>
<?php
//etc. etc.
?>
The basis for this question, is I have some code I wrote a long time ago, and I’ve learned a LOT since then. I want to clean it up a little bit. (things like print($this); print($that); instead of print($this.$that); and the like, include the above.
I just want to make sure that moving to the “uppermost” example is either better, or just a better/cleaner practice way of doing things. I’d hate to move forward with something I think looks cleaner, but is bad for some reason I don’t see
Edit: Sorry for any hiccups with the code, I wrote it on the spot as a simple example
Short answer
DRY (Don’t repeat yourself) is a principle you should be more afraid of instead of “Perfomance”.
Therefore you should go with loops.
Long answer
Consider for an (horrible) moment to have the second code; a long list of the same code repeat over and over again for like 20 times. Let’s just imagine you want to add 10 more: with the first you just change the loop at the beginning (1 line), with the second you create something like 100 more lines of code. Then assume you want to change a bit of each code: with the second you have to edit that piece of code for 30 times, with the first… well I think you got the concept.