3

I want to combine two variables together:

$var1 = 'Welcome ';

$var2 = $_SESSION['UserName'];

Which of these will work faster? Code sample 1:

$var3 = $var1.$var2;

Or code sample 2:

$var3 = "$var1$var2";
Wazy
  • 8,822
  • 10
  • 53
  • 98
  • 4
    Why don’t you benchmark it yourself? – Gumbo Sep 07 '10 at 11:59
  • 1
    If you think it'll make any difference with what I imagine `$_SESSION['UserName']` is likely to contain, you're wrong. – Dominic Rodger Sep 07 '10 at 12:00
  • 2
    possible duplicate of [PHP String concatenation - "$a $b" vs $a . " " . $b - performance](http://stackoverflow.com/questions/1813673/php-string-concatenation-a-b-vs-a-b-performance) – karim79 Sep 07 '10 at 12:01
  • 2
    Does this have a 'real' (read: big loop) background, is it just theoretical or premature optimization? – Bobby Sep 07 '10 at 12:01

2 Answers2

7

Code sample 1 won't work at all..

Syntax considerations set aside, Sample 1 should be trivially faster because it doesn't involve parsing a string (looking for variables).

But it's very, very trivial..

Berzemus
  • 3,618
  • 23
  • 32
  • 4
    +1 Exactly. Sample 1 will generate fewer OPCode instructions, so it will be faster. The string parsing shouldn't matter much (Since it's done by the pre-processor), but it will generate more opcodes. The thing is in either case, we're likely talking about a difference in the sub-microsecond range. So unless you're dealing with literally millions of them inside of tight loops, go for readability first. In this case, the more readable solution just so happens to also be the faster one. A double win! – ircmaxell Sep 07 '10 at 12:07
2

Both examples would provide the same result - $var3 equal to "Welcome Wazzy". However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via concatenating small sets a million times or so), and you will see that concatenation works significantly faster than variable substitution.

Wazy
  • 8,822
  • 10
  • 53
  • 98