Friday, March 13, 2009

PHP: echo vs. print

I found this interesting article at LearnPHPOnline which performs an analysis of using echo versus print to output data. Both print and echo are considered language constructs rather than functions, but print can behave like a function if passed the right parameter. So which should you use? For all intents and purposes, it doesn't really matter that much although echo is slightly faster than print as is demonstrated in the article. I found this bit the most interesting conclusion the authors gleaned from their analysis:

As a last note on speed, it's recommended that developers add strings together via parameters- not through concatenation or multiple Echo calls. Instead of using new Echo commands to help organize code, separate them with commas (Make certain you aren't using concatenation- this actually slows the process)! Calling the Echo or Print command multiple times will also degrade the performance of the script, although marginally, as seen below:


echo "Hello" . "World! <br />";
// Concatenation slows down the process
// because PHP must add strings together

echo "Hello" , "<br />";
echo "World" , "<br />";
// Calling Echo multiple times still isn't
// as good as using Echo parameters solely

echo "Hello" , "World!" , "<br />";
// Correct! In a large loop, this could
// save a couple of seconds in the long run!
?>



The author also makes the point that echo has one less character than print - which means less work for us lazy programmers. :)

No comments:

Post a Comment