Memory usage - Assigning an array to another var by Reference

Discussion in 'PHP' started by powerobject, Mar 27, 2006.

  1. #1
    If I assign a HUGE array to another var by 'reference', would it consume twice the memory of the array? Or is it just a pointer? How much would it add to memory usage on assigning the array to another var by reference within the same class?

    The confusing point is that on doing an unset() of the second var, the first var is still intact - indicating that they are indeed two different vars!

    Thanks,
     
    powerobject, Mar 27, 2006 IP
  2. exam

    exam Peon

    Messages:
    2,434
    Likes Received:
    120
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Using a reference will help memory usage, as the contents is only stored once in memory. A reference is not a pointer, it actually goes to the same contents as the original variable (as opposed to containing a memory address as in C).
     
    exam, Mar 27, 2006 IP
  3. powerobject

    powerobject Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The problem is for following statement. If you execute it, inspect the result carefully:

    $array1 = array("an","array");
    $array2 = & $array1;

    Now if I change anything in $array2, the change will also occur in $array1 as it is a reference of $array1. But lets run this now:

    unset ($array2);

    What should actually happen, as it is a reference of $array1, $array1 should
    be unset. But in practice, $array1 still holds its value while $array2 becomes empty.

    More surprisingly, if you unset the main array like this:

    unset($array1)

    you will find that $array1 becomes empty but $array2 holds the value.

    Is it a Bug or Feature??

    Thanks
     
    powerobject, Mar 28, 2006 IP
  4. exam

    exam Peon

    Messages:
    2,434
    Likes Received:
    120
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I don't know if it's a bug or a feature, but it is the documented way Php works. When you unset a variable it breaks the relationship between the variable and the data stored in memory, but it doesn't erase the memory. It's like when you delete a file off your hard drive. The file is still there (until overwritten by something else), there is just no way of getting to it. With php references, there are simply 2 (or more) variables pointing to the same data, so if one is unset, you still have a way of getting to the data (the other variable.) Hope that helps. Also you might read php's documentation on references.
     
    exam, Mar 28, 2006 IP