views:

339

answers:

5

In PHP, I'm frequently doing lots of string manipulation. Is it alright to split my code into multiple functions, because if primitive types like strings are passed by value I would be significantly affecting performance.

+4  A: 

Only objects are passed by reference.

That doesn't mean you'll get a performance boost by changing to references though - PHP uses copy-on-write, so a copy is only made if you modify the variable.

Splitting your code into functions won't slow it down from that point of view. There is a small overhead for calling a function, but unless your in a loop calling 10,000s of them it's probably not something you need to worry about.

Greg
Objects are not passed by reference. Objects are reference types, but they are passed by value as function parameters unless you specify otherwise.
Joseph
They're not technically passed by reference but close enough. This is true as of PHP 5 - PHP 4 was different.
Greg
+2  A: 

Objects are passed by reference. Everything else is passed by value unless you explicitly use pass-by-reference with the & operator.

That being said, PHP also uses copy-on-write to avoid unnecessary copying.

cletus
+1  A: 

Yes, primitives are passed by value unless you explicitly define the function to pass by reference (by using an ampersand & in front of the parameter) or invoke the function with an ampersand in front of the argument. (The latter of which is deprecated)

See this part of the documentation for more.

EDIT

Also, the statement that "objects are passed by reference" in PHP is a bit of a simplification, though it can often be thought of that way for most purposes. This chapter of the documentation explains the differences.

Peter
+1  A: 

By default, everything is passed by value. If you want to pass something by reference you have to explicitly state it as so.

Here is the php documentation that explicitly states this behavior.

Joseph
+1  A: 

Passing by reference is actually slower than passing by value in PHP. I can't find the correct citation for this claim; it's somewhere in the "References" section of the PHP manual.

orlandu63