PHP Programming

PHP: Echo Versus Print(f)

One of the things I remember about when I started programming in PHP was the confusion I ran in to when deciding how to print text.  Should I use the print construct?  Or maybe I should use the echo construct?  Perhaps the C-style printf function instead?  Eventually most people just latch on to the echo construct because “That’s what everyone else is doing”.  Is that the fastest method to use though? Well, that’s what I’m going to find out.

The Test

The test I decided to use loops 1000 times, and inside the main loop, there is a sub-loop creating the output which runs from 0 to N (where N is the value of the outer-loop counter).

$start = microtime(true);
for($i = 0; $i < 1000; $i++) {
     for($x = 0; $x < $i; $x++) {
          //Output here.
$end = microtime(true);

After the test has been completed, I just wrote the times to a text file for collection later.

The Results

  • echo – 16.470 seconds
  • print – 16.473 seconds
  • printf – 16.432 seconds

As I expected, the difference between print and echo were negligible.  I suspect that they use the same underlying code.  The real surprise was from printf(), which is a function and is supposed to have taken longer because of the overhead of calling it.  I’m at a loss as to why it’s faster than the other two, but the difference isn’t really significant enough to worry about.  If someone wanted to be a bit more scientific about this, this program should be run probably a couple thousand times so that we can get a good sample and see what happens then.

If you would like to run this code yourself and let me know your results, it’s available for download here.

By Jack Slingerland

Founder of Working and living in Raleigh, NC. I manage a team of software engineers and wrk in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and son, lifting weights, and advancing in my free time.