views:

262

answers:

4

I want to know if the below code:

<?php
printf ("%s", $some_variable);
?>

is more efficient than:

<?php
echo "$some_variable";
?>

One common complaint of variable interpolation is that it is very slow. I want to know if there is a better alternative to variable interpolation that doesn't make one's code as messy as:

<?php
echo $first_var, ' some string ', $second_var;
?>
A: 

I don't know how efficient printf is, but if you are looking for a solution that doesn't look as messy as the echoing, I would recommend escaping out of php to print strings then using short tags to print the variables.

?>
...
<?=$first_var?> some string <?=$second_var?>
 ...
<?
Craig
Unfortunately, short tags are not an option for me. Even if they were, I still wouldn't use them because many other programmers frown upon short tags--for good reason.
Rishabh Mishra
+2  A: 

Quick test:

$ cat test-echo.php
<?
$i=10000000;
$some_variable = 'test';
while($i--){
 echo "$some_variable";
}
$ cat test-echo2.php
<?
$i=10000000;
$some_variable = 'test';
while($i--){
  echo $some_variable;
}
$ cat test-printf.php
<?
$i=10000000;
$some_variable = 'test';
while($i--){
  printf ("%s", $some_variable);
}

$ time php test-echo.php > /dev/null

real    0m16.099s
user    0m8.254s
sys     0m4.257s

$ time php test-echo2.php > /dev/null
real    0m15.122s
user    0m6.913s
sys     0m4.037s

$ time php test-printf.php > /dev/null
real    0m48.235s
user    0m30.643s
sys     0m11.614s

So printf significantly is slower than simple echo. echo with variable interpolation is a bit slower than simple echo. Difference in not noticable, probably because of poor test case.

niteria
This benchmark is contrived and narrow. Don't follow it.
orlandu63
+3  A: 

The argument among variable interpolation, string concatenation, multiple-parameter passing, and s?printf is, for a lack of a better word, stupid. Don't worry about this trivial micro-optimization until it becomes the memory/speed bottleneck, which it will never become. So effectively just use whatever you want, factoring in readability, discernibility and plain preference.

orlandu63
Thank you very much for the wise words.I decided that it really is best just to go with whatever is more readable--because an unreadable (but fast) way to print strings would probably end up being worse for me in the long-run.
Rishabh Mishra
+1  A: 

Try checking out http://phpbench.com for a comparison of all the nitpicky micro optimizations.

ryeguy
Thank you very much!While that link doesn't appear to yet answer my original question, it is extremely handy.
Rishabh Mishra