Ok, there has been some discussion on the ZE2 list about returning
references from functions and it has gotten me looking at references in
general.  Phorum deals with some pretty large arrays and so far that has
made us faster than other BB's.  I want to keep it that way.

First, the question: When is it a good idea to use references for
performance reasons?

Now, some things I tried (PHP 4.0.6):

    $arr=array();
    $arr=array_pad($arr, 10000, md5(microtime()));

    function test($arr){
        $newvar=$arr;
        return $newvar;
    }

    $newvar=test($arr);

This code takes 2.6MB of ram to run. Changing the function to any of these:

    function test(&$arr){
        $newvar=$arr;
        return $newvar;
    }

    function test(&$arr){
        $newvar=&$arr;
        return $newvar;
    }

    function test($arr){
        $newvar=&$arr;
        return $newvar;
    }

it now takes 4.4MB to run. That is not what I expected.

Now, this function:

    function test($arr){
        foreach($arr as $key => $var){
            $newvar[$key]=$var;
        }
        return $newvar;
    }

takes 4.4MB also.  I would expect that.  However, changing it to:

    function test($arr){
        foreach($arr as $key => $var){
            $newvar[$key]=&$arr[$key];
        }
        return $newvar;
    }

It now takes 6.8MB of ram.

Last, this code:

    $arr=array();
    $arr=array_pad($arr, 10000, md5(microtime()));

    $arr2=$arr;

uses 2.6MB where:

    $arr=array();
    $arr=array_pad($arr, 10000, md5(microtime()));

    $arr2=&$arr;

uses 3.5MB.


So, my conclusion is that references are bad in all cases on memory and
should only be used when you have to know you are using the same exact data
in two places, or a variable needs to be modified by a function.  If this is
the case, shouldn't this be documented?

Am I missing something?

Brian Moon
------------------------------------------
dealnews.com, Inc.
Makers of dealnews & dealmac
http://dealnews.com/ | http://dealmac.com/



-- 
PHP Development Mailing List <http://www.php.net/>
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]

Reply via email to