On a pure speed measurement, echo is generally considered the fastest as it does not return a value like print or printf does. Being the skeptic that I am, I feel the need to do my own benchmarking; which can be found near the end of this article. But first, let’s look at why 3 different functions exist to perform the same task.
While these three functions all have the same outward function, they are performed in slightly different ways. Echo and print are very similar in that they simply dump whatever they are passed to output. Printf takes it one step further and allows you to format the data before output.
Echo uses the format
echo "Hello, world";. This simply causes the string “Hello, world” to be sent to the browser (or whatever you are outputting to). Nothing is returned so you cannot use the structure
$return = echo("Hello, world");.
Print can be used in much the same way as echo, with one difference. You have the ability to use a return value. Print returns the value 1 if successful, so
$retval = print("Hello, world"); would set $retval = 1. This can be useful if you are doing something more complex than simply outputting text.
PrintF goes up a step on print and allows you to format the text prior to output. The formatting strings are described in the manual page for sprintf.
First, some background. The computer being used for this test is a 650mHz AMD Athlon with 512mb RAM running Mandrake Linux 10.0 and PHP version 4. The timing scripts are being run directly from the command line. All scripts measure the time directly before the testing loop for the start time and directly after the loop for the end time. Each loop is 100,000 iterations and repeated 10 times. These 10 times are divided by 10 to get an average.
For more information on timing scripts, please see one of my other articles.
The commands are:
echo "The quick brown fox jumped over the lazy dog.\n";
print "Thie quick brown fox jumped over the lazy dog.\n";
$var = print("The quick brown fox jumped over the lazy dog.\n");
printf("The quick brown fox jumped over the lazy dog.\n");
$var = printf("The quick brown fox jumped over the lazy dog.\n");
So, which one to use? Looking at these results, it appears that echo and print are really, really close in terms of speed. The difference per command was only 2/1,000,000 of a second. It just comes down to personal preference. I use echo because that’s what I used first. The speed drop on print appears to come when you assign a variable, at which point the command speed drops 1/100,000 of a second, which is still fairly minor.