views:

49

answers:

4

Hi everyone,

Will there be any measurable performance difference when passing data as values instead of as reference in PHP?

It seems like few people are aware of that variables can be passed as values instead of references. Is this common sense or not?

+1  A: 

If there is a performance difference, it's negligible. Don't worry about these sorts of micro-optimizations unless you know that passing by reference is causing a performance hit (except I can't imagine a situation where that is true).

On a side note, people generally advise against passing arguments by reference because it encourages bad design, much like using global variables does.

I'm not sure what you meant by the last part, though. PHP passes arguments by value by default.

musicfreak
+1  A: 

If you are passing a large variable by value (which is the default for everything except objects in PHP5+), then yes, you can take a performance hit.

For example, if the user submits a large amount of POST data, if you were to pass that to a function normally (aka pass by value), the whole array would have to be copied, which would affect performance. However, unless you're on a very large-scale site, you probably won't notice the hit.

Pass by reference is possible in PHP, but certainly not the default (unless it's an object): you need to add an & before the variable to make it pass by reference, otherwise it's just by value (and copies it). As of PHP5, objects are passed by reference automatically, but before PHP5 you need to explicitly pass by reference (ie add the &)

Timothy Armstrong
+2  A: 

From my understanding, PHP 5 passes simple data types and arrays by value, but when it comes to objects it passes by reference. It seems this is a behaviour you should be aware of - I assume arrays are passed by value and therefore large ones may well incur a performance hit if you do not require a copy to be made.

I've seen plenty of arguments against passing by reference explicitly and letting PHP do its thing.

Also, if you want to pass an object by value then you should clone it, ideally.

Geoff Adams
+1  A: 

Objects are always passed by reference if you use a recent version of PHP. As of the other type, the main concern are the strings / array. For those it depends. PHP's implementation of strings makes that if you don't modify the string you are passing to the function's argument (you only read it / scan it), it never will be copied. The implementation is called "copy-on-write". I'm not sure about array, I'll need some test to answer this.

Unless you modify the passed by value string argument, there will be no difference with the passed by reference.

Savageman