What is better / faster:
For example:
STATIC / direct HTML:
<?php
for($i=0;$i<$sth;$i++) {
?>
<tr>
<td>
<?php echo $content; ?>
</td>
</tr>
<?php
}
?>
OR
PHP generated HTML:
<?php
for($i=0;$i<$sth;$i++) {
echo "<tr><td>".$content."</td></tr>";
}
?>
Does it matter which option i choose?
Thanks
It's not so much a matter of speed which may vary based on use case, but of making the code clean and maintainable. Actually both examples make for code that's hard to maintain and read.
I'd suggest using a simple and lightweight templating engine to separate all logic from presentation.
I think that there is no substantial difference between the two, the question should be "Which one is more readable" IMHO and i think that using php and html inline is far less readable than echoing php. But that's just my idea.
The better: Generated html.
Generated html with php is far more easy to maintain and easier to read.
The faster: There is no significant speed difference. However on large dynamic websites where content is loaded from a database etc things might take a fraction of a second more time to output. However, the time you spend on updating a static html file is a lot more than editing dynamic content..
Go dynamic :]
In this case "PHP generated HTML" would be quicker because you are only doing one echo where as in "STATIC / direct HTML" you are doing $sth echos. If $sth is zero then "STATIC / direct HTML" would be quicker.
But seriously, the page is parsed and optimised/normalised so it doesn't make any difference. Parsing with less might be quicker because there are less context switches but this is the smallest part (compared to running it) so it makes negligible difference.
Just pick the style that you feel comfortable with.
Two codes represent the same thing, not differentiate in the speed , But the second code may be a little faster because the code does not contain more than one entry and exit signs.
<?php ?>
this will be carried out faster .
The first approach should be faster as it does not involve a lot of string concatenation. It's also better in terms of code readability.
I think the first solution:
It is clearer and do not require php elaborations with string to dispplay simple static content
Related
I'm rather new to programming and i know how to separate PHP from HTML, but i would like to know if there is any difference in doing
this:
<?php $rand="I love apples" ?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<?php echo"The variable contains the string $rand"; ?>
</div>
?>
compared to doing this:
<?php
echo "<h1>This is a title</h1>";
echo "<div>";
echo "<p>This is a paragraph</p>";
echo "The variable contains the string $rand";
echo "</div>";
?>
Is there any difference between in performance etc, between splitting the PHP code from the HTML code and just echoing the whole page in php?
The best practice is not to seperate PHP from HTML, the best practice is to seperate logic from markup.
Also important is coding style. Proper line indentions. Using echo "</div>"; instead of echo"</div>";, valid HTML, not putting variables into quotations:
echo "The variable contains the string $rand";
better (why? see my comment below):
echo "The variable contains the string ",
$rand,
" :-)";
Your whole project gains much quality and worthness just by improving the code, writing clean, readable, maintainable. Imagine you want to change the Text, you would have to add or change lots of echoes.
Code Style Guides > Pear,
PSR, Zend <
encourage developers to keep their code readable, valid and cross-browser compatible
The problem is not performance, it's about readability and more importantly, maintainability.
Doing all the processing in one place, and all of the output in another (i.e. Logic and Presentation), would mean you will have an easier time altering one without affecting the other too drastically.
To your specific question, the top method is preferable by far, for the reasons listed above.
Taking your question at face value, there are two reasons that come to mind immediately:
Assuming you're using a smart editor, echoing all your HTML will cause you to lose syntax highlighting for it, so you're less likely to catch errors.
Because everything is inside a PHP string, now you have to worry about escaping all your other special characters. Try spitting out some Javascript with a string in it and let us know how fun that is.
However, when most people say something like "separating PHP from HTML" they are referring to the concept of separating your logic from your views. It means don't put complex business logic, computations, and database calls inside your html pages. Keep that all in pure PHP files, and have your html files contain minimal PHP that's only used to spit out your data.
<?php $rand="I love apples" ?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<?php echo"The variable contains the string $rand"; ?>
</div>
?>
The above looks poorly separated. This is what php/html separation should look like:
<?php
$rand="I love apples";
?>
<h1>This is a title</h1>
<div>
<p>This is a paragraph</p>
<p>The variable contains the string <?=$rand ?></p>
</div>
Performance-wise, that's not an issue but it would do much favor for programmers to be able to read the code easily, hence the need for HTML/PHP separation practices. Ideally, if you're going to do just one script, keep all your PHP code at top. Also, other reason for the separation is that IDE editors can easily format HTML nicely. If there's a HTML tag inside the PHP tag that is ending with a HTML tag outside of PHP, then HTML cannot be formatted correctly. For example:
<div><p>And it offers so much <?php echo "$features</p>
<h2>Proven Ideas";?></h2>
<p>More details ahead</p>
</div>
The above will run just fine but the IDE html formatter will likely be confused with missing end tags and won't format making it more difficult for programmers to read them.
I think you example is not a good one that makes it very clear why you should separate it.
The reason why you should separate not just HTML but the presentation, rendering or UI part of your application is clean coding and separation of concerns. This will make sure your get clean, easy to read code and makes your application maintable.
Take Wordpress for example, it is an extremely fugly mix of php and HTML. They even do SQL queries in the presentation layer of the application, if you can even draw a borderline between presentation and other logic in this thing.
You'll always have to output some dynamic content in your HTML but really try to reduce it to echoing variables and having some output formatting helper objects there. All business logic should be somewhere else, just not in the "templates" or whatever else you'll call the files that contain the output.
Have a look at the MVC pattern for example, it gives you a good idea of how and why you want to separate things.
In my opinion, it depends on the level of HTML formatting that is being done versus PHP logic. Nothing more & nothing less. It’s simply easier to read pure HTML as pure HTML or PHP as straight PHP. When it is all jummbled together—the way some templating systems handle it—it becomes a logical headache to read & debug. So I err on the side of placing HTML in PHP for my own sanity’s sake.
Unclear on the performance pluses or minuses if there are any. But can assure you that in 20+ years I have never had a server slow down because of too much HTML embedded in PHP
Personally, I would format your code example like this:
<?php
echo "<h1>This is a title</h1>"
. "<div>"
. "<p>This is a paragraph</p>"
. "The variable contains the string $rand"
. "</div>"
;
?>
I like this method since there is one echo—which makes it clear what is happening—and the rest of the HTML is just concatenated via . characters.
Also, remember all formatting in programming benefits HUMANS more than anything. A computer only needs to see the commands, so if you want to be pitch perfect for a machine, just code without any spaces or formatting. Heck, stop using full words & just use 1 letter variables! Oh wait, that is how it was done in ye olden days.
Nowadays compilers & caching systems are designed to take human readable code & make it machine optimized.
Which is all to say: You should code towards readability & logic on your part. Nothing more & nothing less.
Is there any advantages/disadvantages to either of these statements over the other one:
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
echo "<p>Hello World</p>";
?>
OR
<?php
$test = 1;
$test2 = 2;
$test3 = $test + $test2;
?>
<p>Hello World</p>
What i'm asking is, if i'm outputting a page using PHP should i keep closing the php tags and stick normal HTML in or echo out the HTML? Which is better?
if you want do be realy exact, there are three options:
the slowest:
echo "<p>Hello World</p>";
a bit faster (no need to check for inline-valiables because of single quotes):
echo '<p>Hello World</p>';
the fastest (no php-interpreting at all):
<p>Hello World</p>
but between all of this, the difference would be so minimalistic that you won't ever notice it - much more important: make your code redable and do it the same way everywhere, so nobody who's reading your code (and has to maintain it) gets confused. i personally would prefer the third method (so i can use code-completition in my IDE), but it's your choice - i know a lot of people who output everything using echo.
EDIT: to be complete, there are some more possibilitys i didn't mentioned like heredoc- and nowdoc-syntax, but this are basically the same as double/single-quotes... also, you could write print instead of echo and so on, but that wouldn't make a difference.
Method 2 is cleaner IMHO because you separate PHP code from HTML. Your IDE (if you use any) can parse your HTML tags and autocomplete them, and spot any typo's.
I'm not a PHP programmer but I would assume the 2nd method is faster, because PHP doesn't have to process the echo language construct, allocate buffer and all that stuff. It is also cleaner, and less of a hassle to modify the HTML.
Also, it would be wise to learn to use a template engine for your HTML in order to separate concerns. Smarty was popular a couple years ago, I don't know if it's still is.
Although the difference is negligible, you should stick normal outputing out of PHP tags. Echo command will have to be parsed by PHP interpreter and then sent as output.
The only difference is that with echo(); you instruct PHP to process the code, otherwise, there is no difference at all.
One way or another, the result is exactly the same and for performance, there is almost no differences at all. Like... How much time PHP needs to process that echo();? I think with miliseconds you could run in problems calculating numbers that small. Hehe.
For the most part, when I want to display some HTML code to be actually rendered I would use a 'close PHP' tag, write the HTML, then open the PHP again. eg
<?php
// some php code
?>
<p>HTML that I want displayed</p>
<?php
// more php code
?>
But I have seen lots of people who would just use echo instead, so they would have done the above something like
<?php
// some php code
echo("<p>HTML that I want displayed</p>");
// more php code
?>
Is their any performance hit for dropping out and back in like that? I would assume not as the PHP engine would have to process the entire file either way.
What about when you use the echo function in the way that dose not look like a function, eg
echo "<p>HTML that I want displayed</p>"
I would hope that this is purely a matter of taste, but I would like to know if I was missing out on something. I personally find the first way preferable (dropping out of PHP then back in) as it helps draw a clear distinction between PHP and HTML and also lets you make use of code highlighting and hinting for your HTML, which is always handy.
The first type is preferable, exactly for the reasons you mentioned.
Actually, echoing out whole chunks of html is considered bad practice.
No, there's no performance increase that would be visible.
Sometimes its just simply easier to output content using echo (for example, when inside a while or for loop) than to close the php tag.
I think there's a preprocessor which converts the same form into the second. That's what happens in ASP.NET, anyway. And in both ASP.NET and classic ASP, loops can actually stretch across raw-HTML regions.
There's no performance difference at all.
Just the style that produces the most readable code. Depending on the actual situation that can be either of the two.
But mixing HTML and PHP should be avoided where possible anyway. THis can be accomplished by using a template system for your views.
So I've always developed PHP pages like this: <?php goes at the top, ?> goes at the bottom, and all the HTML gets either print()ed or echo()ed out. Is that slower than having non-dynamic html outputted outside of <?php ?> tags? I can't seem to find any info about this.
Thanks!
--Mala
UPDATE: the consesus seems to be on doing it my old way being hard to read. This is not the case if you break your strings up line by line as in:
print("\n".
"first line goes here\n".
"second line goes here\n".
"third line");
etc. It actually makes it a lot easier to read than having html outside of php structures, as this way everything is properly indented. That being said, it involves a lot of string concatenation.
I'm not sure about speed, but it's typically best practice to separate dynamic elements and the display of them.
Check out a framework like CodeIgniter: This has a "controller" and a "model" that grab data, sort it or do whatever you like with it, and then feed it to a "view" (some sort of template).
This paradigm is called MVC, and is a really, really valuable thing to learn about. I've found its chief advantage to be easier-to-maintain code. I don't end up with a monster document that I have to re-learn each time I approach it.
Resources:
CodeIgniter
MVC
The difference in speed is probably negligible, however, when **print()**ing out all of your HTML with PHP, the code can get very ugly, and makes it much harder to read than if you just have plain HTML.
Edit: Also, if you're are **print()**ing out static HTML that doesn't change, really what is the point? It gives you no added benefit.
Pros
None that I can see
Cons
Code that is hard to read
One more step in processing for the PHP engine, which although probably not noticeable, it is an extra step.
The speed is negligible - trust me, this will not be your bottleneck.
Along with any other MVC framework, you might want to check out a simple templating system, such as Smarty, which separates your PHP logic from your HTML and also does caching.
I don't know if it's slower or faster, but (in my opinion) it makes the code a lot more difficult to understand. Which I guess is why I don't typically do it.
It is almost the same from a performance point of view.
I would set the focus on the readability of the code. If you have a performance problem, figure out the bottleneck and cache it.
Is that slower than having non-dynamic html outputted outside of <?php ?> tags?
Well yes, it is... marginally. But that's not really the issue: it's all about the readability.
this way everything is properly indented
Your example isn't indented at all, which is fairly typical for the print-heavy, PHP I've unfortunately had to maintain!
Try this approach to keeping good, consistent indentation:
<ul>
<?php
// block of arbitrary code blah blah
//
$conditions= get_conditions_from_request();
$isadmin= $user->privileges>=PRIV_ADMIN;
?>
<?php foreach (select_things($conditions) as $thing) { ?>
<li>
<strong><?php h($thing->title); ?></strong>
<?php if ($isadmin) { ?>
<a href="/editthing.php?id=<?php u($thing->id); ?> (Edit) </a>
<?php } ?>
<?php h($thing->description); ?>
</li>
<?php } ?>
</ul>
(This presumes a function h that calls echo htmlspecialchars and u that does echo htmlspecialchars urlencode. Getting this escaping stuff right is essential to having a secure site, and is something that's almost always wrong in print-based PHP, as it tends to use "blah $var blah"-style templating without any escaping at all.)
Maybe not the best practice, but I choose to mix and match print() statements. For large chunks of layout code, I don't use print(), but if I'm rendering a complex if/else or for/while block and I'd be exiting the PHP block every other word, then I'll print out the non-dynamic text with the dynamic text.
Performance is very negligible at best. You can create a page, and put a timer on it. (Here is a tutorial on creating a script timer)
Output the exact same data both ways, and measure it with as many samplings as you can get, this should roughly tell you which is faster. I'm guessing very close to the same.
I have seen a lot of these pages with PHP embedded inside HTML, and I don't like it. As Alex Mcp suggested you should be thinking about a MVC model.
The problem with scripts embedded into html is the flow control and logic aren't easy to read, and there are some wierd problems that occur here and there. The best solution for me is usually to use Smarty or the Zend Framework to create template pages and then swap the data that goes in and out. Much easier to manage in the long run.
What is more efficient and/or what is better practice, to echo the HTML or have many open and close php tags?
Obviously for big areas of HTML it is sensible to open and close the php tags. What about when dealing with something like generating XML? Should you open and close the php tags with a single echo for each piece of data or use a single echo with the XML tags included in quotations?
From a maintenance perspective, one should have the HTML / XML as separate from the code as possible IMO, so that minor changes can be made easily even by a non-technical person.
The more a homogeneous block the markup is, the cleaner the work.
One way to achieve this is to prepare as much as possible in variables, and using the heredoc syntax:
// Preparation
$var1 = get_value("yxyz");
$var2 = get_url ("abc");
$var3 = ($count = 0 ? "Count is zero" : "Count is not zero");
$var4 = htmlentities(get_value("def"));
// Output
echo <<<EOT
<fieldset title="$var4">
<ul class="$var1">
<li>
$var2
</li>
</ul>
</fieldset>
EOT;
You will want to use more sensible variable names, of course.
Edit: The link pointed out by #stesch in the comments provides some good arguments towards using a serializer when producing XML, and by extension, even HTML, instead of printing it out as shown above. I don't think a serializer is necessary in every situation, especially from a maintenance standpoint where templates are so much more easy to edit, but the link is well worth a read. HOWTO Avoid Being Called a Bozo When Producing XML
Another big advantage of the separation between logic and content is that if transition to a templating engine, or the introduction of caching becomes necessary one day, it's almost painless to implement because logic and code are already separated.
PHP solves this problem by what is known as heredocs. Check it out please.
Example:
echo <<<EOD
<td class="itemname">{$k}s</td>
<td class="price">{$v}/kg</td>
EOD;
Note: The heredoc identifer (EOD in this example) must not have any spaces or indentation.
Whichever makes sense to you. The performance difference is marginal, even if a large echo is faster.
But an echo of a big string is hard to read and more <?php echo $this->that; ?> tell a story :)
echo sends its argument further down the request processing chain, and eventually this string is sent to the client through a say, network socket. Depending on how the echo works in conjunction with underlying software layers (e.g. webserver), sometimes your script may be able to execute faster than it can push data to the client. Without output buffering, that is. With output buffering, you trade memory to gain speed - you echos are faster because they accumulate in a memory buffer. But only if there is no implicit buffering going on. One'll have to inspect Apache source code to see how does it treat PHPs stdout data.
That said, anything below is true for output buffering enabled scripts only, since without it the more data you attempt to push at once the longer you have to wait (the client has to receive and acknowledge it, by ways of TCP!).
It is more efficient to send a large string at once than do N echos concatenating output. By similar logic, it is more efficient for the interpreter to enter the PHP code block (PHP processing instruction in SGML/XML markup) once than enter and exit it many times.
As for me, I assemble my markup not with echo, but using XML DOM API. This is also in accordance with the article linked above. (I reprint the link: http://hsivonen.iki.fi/producing-xml/) This also answers the question whether to use one or many PHP tags. Use one tag which is your entire script, let it assemble the resulting markup and send it to the client.
Personally I tend to prefer what looks the best as code readability is very important, particularly in a team environment. In terms of best practice I'm afraid I'm not certain however it is usually best practice to optimize last meaning that you should write it for readability first and then if you encounter speed issues do some refactoring.
Any issues you have with efficiency are likely to be elsewhere in your code unless you are doing millions of echo's.
Another thing to consider is the use of an MVC to separate your "views" from all of your business logic which is a very clean way to code. Using a template framework such as smarty can take this one step further leading to epic win.
Whatever you do, don't print XML!
See HOWTO Avoid Being Called a Bozo When Producing XML
I've made myself the same question long time ago and came up with the same answer, it's not a considerable difference. I deduct this answer with this test:
<?
header('content-type:text/plain');
for ($i=0; $i<10; $i++) {
$r = benchmark_functions(
array('output_embeed','output_single_quote','output_double_quote'),
10000);
var_dump($r);
}
function output_embeed($i) {
?>test <?php echo $i; ?> :)<?
}
function output_single_quote($i) {
echo 'test '.$i.' :)';
}
function output_double_quote($i) {
echo "test $i :)";
}
function benchmark_functions($functions, $amount=1000) {
if (!is_array($functions)||!$functions)
return(false);
$result = array();
foreach ($functions as $function)
if (!function_exists($function))
return(false);
ob_start();
foreach ($functions as $idx=>$function) {
$start = microtime(true);
for ($i=0;$i<$amount;$i++) {
$function($idx);
}
$time = microtime(true) - $start;
$result[$idx.'_'.$function] = $time;
}
ob_end_clean();
return($result);
}
?>