tags:

views:

186

answers:

3

which one of the 2 have the best performance?

In javascript I was heard douglas crockford say that you shouldn't use str += if you are concatenating a large string but use array.push instead.

I've seen lots of code where developers use $str .= to concatenate a large string in PHP as well, but since "everything" in PHP is based on arrays (try dumping an object), my thought was that the same rule applies for PHP.

Can anyone confirm this?

+1  A: 

array_push() won't work for appending to a string in PHP, because PHP strings aren't really arrays (like you'd see them in C or JavaScript).

Chris
this does require a join('', array) agreed, but you can do the following just fine:$arr = array();array_push($arr, "hello");array_push($arr, "world");echo join(' ', $arr);and it will give you a string like this "hello world"
kristian nissen
+2  A: 

.= is for strings.

array_push() is for arrays.

They aren't the same thing in PHP. Using one on the other will generate an error.

cletus
The OP was referring to the technique of pushing your strings onto an array, and then using the array's join method to combine them into a single string. In languages without mutable strings this tends to a faster operation since you're not reallocating for a new string on each concatenation.
Alan Storm
+4  A: 

Strings are mutable in PHP so using .= does not have the same affect in php as using += in javascript. That is, you will not not end up with two different strings every time you use the operator.

See:

http://stackoverflow.com/questions/124067/php-string-concatenation-performance http://stackoverflow.com/questions/496669/are-php-strings-immutable

Lawrence Barsanti