Reputation: 4510
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;
?>
Upvotes: 1
Views: 1220
Reputation: 66851
Try checking out http://phpbench.com for a comparison of all the nitpicky micro optimizations.
Upvotes: 1
Reputation: 7779
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.
Upvotes: 5
Reputation: 1395
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.
Upvotes: 3
Reputation: 7671
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?>
...
<?
Upvotes: 0