0

Like:

$arr1['X'] = 5;
$arr2['Y'] = &$arr1['X'];
$arr1['X'] = 7;

print $arr2['Y']; // prints 7

I tried this and I don't see any memory usage decrease (my array has ~1000 entries), so I guess PHP makes a clone of the array or something? So technically its not really a reference, is it?

My array has sub-arrays (key=>value pairs) instead of numbers. I noticed that if I make them objects, memory usage is lower (~2MB less)

5
  • It isn't clear from your example where you expected to see a memory usage decrease. Can you explain in more detail? Commented Jul 21, 2012 at 0:56
  • well, I was thinking that if a variable references another variable, instead of taking its value normally, the used memory should decrease :P Commented Jul 21, 2012 at 0:59
  • 3
    But a reference still takes up memory. Instead of storing the actual value, it now has to store the memory address of the value it points to, which in some cases may actually take more memory to store than the actual value itself. Commented Jul 21, 2012 at 1:00
  • Yes, but I don't think it takes more in my case. My value is an array with 5 keys, each having a string value of ~20 characters. There's no way a reference to such an array takes more memory than the array Commented Jul 21, 2012 at 1:06
  • You'd be surprised... PHP variables are rather large. My guess in any case is that you would need many more of these variables (100k? 1M?) to be able to distinguish the difference. But post the complete code and your actual benchmarks results, we could look at it and try to figure out if something odd is happening. Commented Jul 21, 2012 at 1:15

1 Answer 1

1

If you issue:

$arr2 = &$arr1;

You reference the whole array, and it should consume less memory. You can measure it with XDEBUG for instance, which I assume is what you are using.

Sign up to request clarification or add additional context in comments.

2 Comments

actually I'm using memory_get_usage
This: xdebug.org/docs/execution_trace, opening the output file with vim.org, is a great way to check your memory consumption, it helped me a lot =) Check the show_mem_delta=1 configuration parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.