0

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
kristian nissen
  • 2,809
  • 5
  • 44
  • 68
  • 2
    "everything" isn't really array based in PHP. They just use the same format for var_dump() and print_r() whether you pass an array or object. – Chris Tonkinson Jun 24 '09 at 13:05

3 Answers3

5

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:

php String Concatenation, Performance Are php strings immutable?

Community
  • 1
  • 1
Lawrence Barsanti
  • 31,929
  • 10
  • 46
  • 68
3

.= 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
  • 616,129
  • 168
  • 910
  • 942
  • 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. – Alana Storm Jun 24 '09 at 15:46
1

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 Tonkinson
  • 13,823
  • 14
  • 58
  • 90
  • 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 Jun 24 '09 at 13:07