views:

94

answers:

3

In PHP, When we get to the optimization phase of the application (I am speaking about an app that handles hundreds of thousands of users) would it be smart to pass all arrays (where I do not mind what happens to them after I pass them to the function) by ref?

+5  A: 

Probably not, there's likely bigger performance hits elsewhere.

Profile your application. Never trust anyone except your profiler to tell you what to optimize.

Sometimes the oddest pieces of code use up most of the execution time, and without knowing exactly where the bottlenecks are, you might spend a long time optimizing away 0.01% of the execution time.

Ben S
Any suggestions for a good PHP profiler?
Itay Moav
I haven't played around enough with PHP profilers to suggest one. From a few questions on SO (http://stackoverflow.com/questions/133686/what-is-the-best-way-to-profile-php-code http://stackoverflow.com/questions/145402/can-you-recommend-peformance-analysis-tools-for-php), XDebug seems to have a good reputation.
Ben S
I agree, minor changes like there are more often snake oil than performance improvements, especially when you talk about compiled languages (yes I know this is PHP).If you are this concerned about memory usage and performance there are more beneficial changes, some of which you won't like such as: not using objects or classes (they're not efficient in PHP 5.x and I haven't ran any benchmarks of PHP 6 yet).
TravisO
A: 

This article http://derickrethans.nl/files/phparch-php-variables-article.pdf suggests this proposed optimization won't make any difference given the way arrays are implemented, and may actually slow things down.

MZB
A: 

PHP arrays have copy-on-write semantics. That means that new memory isn't allocated for the new array until it is modified. For example:

$a = array(1,2,3);
$b = $a; // $b points to the same memory locations as $a
$b[1] = 4; // $b is copied and the modification is performed

Passing by reference might make a difference if the arrays are passed around between a lot of different methods and constantly modified in all these localized scopes. However, that would change the semantics of the application which means that this change is only possible if the arrays aren't being modified.

That means that there's no advantage at all to passing the arrays as references. Don't do it.

Emil H