Thursday, March 1, 2007

Textout with PHP, which one is really the fastest?

(This is a bit off-topic from Agent55). The other day I saw a discussion on a forum about what php-code to use if you want your script to be as FAST as possible. The discussion was about whether "print" or "echo" should be used, and I thought that probably the <php ?> tags would be faster to use than either of print and echo.

Which is faster? (With faster I mean the one that executes in less time)

Hi <?=$username?> !!!

or
<?echo "Hi $username !!!"?>

Ofcourse I had to make an empirical test, to know for sure what method was the fastest, So I hacked up these two (in functionality) identical code-snippets.

The "echo-method"

<?$username="test";$time_start = microtime(true);
for($i=0;$i<1000000;$i++){?><?echo "Hi $i $username !!!"?><?}
$time_end = microtime(true);
?><?=($time_end - $time_start)?>


The "inline-method"
<?$username="test";$time_start = microtime(true);
for($i=0;$i<1000000;$i++){?>Hi <?=$i?> <?=$username?> !!!<?}
$time_end = microtime(true);
?><?=($time_end - $time_start)?>


The results
I have tested these two php-snittets in two single php-files on my test-server and the results are conclusive. Not ONCE did the "echo-method" prove to be faster than the inline-method. In my particular test-case, the "inline-method" was around 0.5 seconds faster than the "echo-method"

Conclusion
So what is the conclusion of this then? Well, in a normal php-development case you won't have to care about these two differences because in my test-code I did 1 miljon repeats of the code to get a difference of only half a second between the two, so this is only a test of the principle.

What I do know is that the "inline-method" is a much more appreciated way to create dynamic content, at least by almost any web-designer I have talked to about this.
So now when it proved to be slightly faster than the "echo-method", I see no reason to use the "echo-method" any longer generally speaking, there will always be exceptions to this ofcourse.

What do you think? Feel free to use the code-snippets above to test them on your own server.


Digg!

2 comments:

Anonymous said...

Well the tags are faster even when you use:
echo 'Hi '.$i.' '.$username.' !!!';

My benchmark - to save time I only did 100000 repetitions.

Tags:
0.78856897354126
0.80873894691467
0.79169297218323
0.81423306465149
0.85763502120972

double quote:
0.84503102302551
0.85157322883606
0.84105587005615
0.92721104621887
0.89898300170898

single quote:
0.81719994544983
0.86846590042114
0.83455610275269
0.82091593742371
0.85013604164124

Anonymous said...

Seems ok for one line of code, but what if you had a template with several of these ... seems like it would be kicking in and out ... i still like the echo method ... why oh why ...