Re: Concatenation vs. Interpolation

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 8/11/07, AmirBehzad Eslami <behzad.eslami@xxxxxxxxx> wrote:
> Hi,
>
> FASTER CODE!
>
> This question involves Coding Style, Readability, Write-ability and
> Performance.
> Some people use the . operator to concat an string to a variable, some
> people use interpolation (embeding variable into string).
>
> =====================
> 1st Method (Concatenation)
> $str = 'My name is ' . $name;
>
> 2nd Method (Interpolation)
> $str = "My name is $name";
> =====================
>
> I know that the 1st Method is much faster, according to
> some benchmarks, which one of them is available
> in the book "Advanced PHP Programming, page 470".
>
> Could we consider the 1st Method as a "Best Practice", which offers
> better Performance?
>
> I know that the performance here is not very much, but is it
> considerable in a high-traffic website?
>
> Thank you in advanced for sharing your opinions,
> Behzad
>

Code readability is quite important when working with a team on a
project, and if you got for method 1 on things like this:
$str = '<a href="'.$url."'>';
It gets quite inreadable, having a double qoute next to a single quote.
while this looks much better:
$str = "<a href='$url'>";

I just did some benchmarks myself, and you can see that concatenation
is definitly a little bit fast, but it's only 2 seconds on 10 million
loops:
For 10,000,000 loops:
Concatenation single quote:5.62786102295
Concatenation double quote:5.63359999657
Interpolation:7.32201290131

Test code used:
<?php

$x = 0;
$str = '';
$add = '?';

$time[1] = microtime(TRUE);
for($x = 0; $x < 10000000; $x++) {
	$str = '<a href="'.$add.'">';
}
$time[2] = microtime(TRUE);

$x = 0;
$str = '';
$add = '?';

$time[3] = microtime(TRUE);
for($x = 0; $x < 10000000; $x++) {
	$str = "<a href='".$add."'>";
}
$time[4] = microtime(TRUE);

$x = 0;
$str = '';
$add = 'def';

$time[5] = microtime(TRUE);
for($x = 0; $x < 10000000; $x++) {
	$str = "<a href='$add'>";
}
$time[6] = microtime(TRUE);

echo 'For 10,000,000 loops:';
echo '<br />Concatenation single quote:'.($time[2]-$time[1]);
echo '<br />Concatenation double quote:'.($time[4]-$time[3]);
echo '<br />Interpolation:'.($time[6]-$time[5]);

?>

Tijnema

-- 
Vote for PHP Color Coding in Gmail! -> http://gpcc.tijnema.info

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux