Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way to write this code is most the efficient?

Tags:

html

php

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?

like image 319
StudioTime Avatar asked Jan 19 '12 17:01

StudioTime


People also ask

What is the most efficient code?

C++ is one of the most efficient and fastest languages.

Why do we write efficient code?

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.


2 Answers

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 //... ?>
like image 190
Rocket Hazmat Avatar answered Sep 28 '22 12:09

Rocket Hazmat


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.

like image 25
Dan Simon Avatar answered Sep 28 '22 11:09

Dan Simon