Jul 31, 2009

////

PHP Echo Vs Print

Echo and Print work in a very similar way but for all intents and purposes are the same. They differ based on how they are structured. Print returns a value much like a normal function would. But despite common belief, Print is not a function, as we can see by the fact that it doesn’t require parenthesis to work (Not to be confused with Printf). Print and Echo are actually both called language constructs, although this isn’t to say that we can’t make Print act like a function.

1
2
3
4
5
<?php
print 'Tagabukid™<br/>';
echo
'Tagabukid™<br/>';
//returns 'Tagabukid™' on two separate lines.
?>


1
2
3
4
5
<?php
print ('Tagabukid™<br/>');
echo (
'Tagabukid™<br/>');
//returns 'Tagabukid™' on two separate lines.
?>

Notice: they are identical in output in either with or without parenthesis...

Which is faster?

Having learnt this, I decided to do some benchmarking to see which one is faster. In my tests, I loop a print/echo execution four million times. The reason for doing it so many times was to get large enough time values to make a significant comparison.

I ran each test a number of times and worked out a rough average in my head. However, the numbers produced were different enough in each iteration to clearly see that one method was faster than another.
Print, Executed in : 13.3383760452 seconds
Echo, Executed in : 9.9976708889 seconds
As a conclusion based on the above output, Echo is basically faster than print. In actuality, the speed difference between Print and Echo would be infinitesimal, it's only when we loop through thousands of times or more that we can see and measure any real difference.

Below is the benchmarking code I used to conduct this test.

1
2
3
4
5
6
7
8
9
<?
$starttime
=microtime(true);
for(
$i=0;$i<=4000000;$i++){
ob_start();
echo
'HelloWorld!<br/>';
ob_get_clean();
}
echo
'Executed in: ',microtime(true)-$starttime,' seconds';
?>


1
2
3
4
5
6
7
8
9
<?
$starttime
=microtime(true);
for(
$i=0;$i<=4000000;$i++){
ob_start();
print
'HelloWorld!<br/>';
ob_get_clean();
}
echo
'Executed in: ',microtime(true)-$starttime,' seconds';
?>

0 Reactions to this post

Add Comment