If I am inside a ton of PHP code, instead of coming out of PHP I usually write code which contains variables like so:
echo "This is how I use a ".$variable." inside a string";
but is it more efficient to actually get out of PHP like so:
?>
Should I instead use the <? echo $variable; ?> like this
<? // then back into PHP
Throughout a page there will be lots of instances of code like this as I fill pages with dynamic content, or is this too much of a generalisation?
C++ is one of the most efficient and fastest languages.
Writing Efficient CodeIt allows you to speed up your development time and makes your code easier to read, debug and maintain. There are a number of different ways in which you can make your code more efficient, including: Use of loops for repeated actions. Use of data structures instead of separate variables.
I only suggest breaking out of php tags when echoing HTML, not just a string.
This is fine for just a string:
// You don't need to concat, double quotes interpolate variables
echo "This is how I use a $variable inside a string";
But with HTML, personally, I like to do this:
<?php //... ?>
<div>
<span>This is how I use a <?=$variable?> inside HTML</span>
</div>
<?php //... ?>
Using echo appears to be slightly faster. I made this simple benchmark script:
<?php
$variable = "hello world";
$num = 10000;
$start1 = microtime(true);
for ($i = 0; $i<$num;$i++) {
echo "test " . $variable . " test\n";
}
$time1 = microtime(true) - $start1;
$start2 = microtime(true);
for ($i = 0; $i<$num;$i++) {
?>test <?php echo $variable;?> test
<?
}
$time2 = microtime(true) - $start2;
echo "\n$time1\n$time2\n";
The echo
loop was consistently about 25% faster.
In reality this difference is so minor it wouldn't have any impact on overall performance unless you were literally doing millions of such output statements. I would still recommend using echo
just because it's more straightforward and easier to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With