2

If I have an array which is using numerical keys and I add a key far outside the range so far, does it create the intermediate keys as well. For example if I have

$array = array(1,2,3,4);
$array[9] = 10;

Will this cause php to internally reserve memory for the keys 4-8 even though they don't have a value with them.

The reason I ask is I have a large 2D array which I want to use for memoization in a dynamic programming algorithm because only a small number of the total cells will need to be computed. However it would be taxing on the memory to have an empty array of that size for the full 2D array. Is there a better way to do 2 key memoization? I could use an associative array and append the keys with a separator or some scheme like that but if php won't make the extra keys I would rather (for simplicity and readability) just use the 2D array. Thoughts?

2
  • It won't consume memory between 4-8 internally. Commented Aug 8, 2014 at 20:09
  • Figure it out! Hit Ctrl+Shift+Esc, select Performance tab and look at the Memory area (bottom). In PHP create an empty array and then set a big key, such as $arr[PHP_INT_MAX]=null;. In order to actually see it you may have to halt the script for a while, e.g. sleep(5);. Commented Aug 8, 2014 at 20:16

3 Answers 3

2

This may not fully answer your question, but should help in finding an answer, at least to the first question.

Create this program.

$arr = array(1, 2, 3, 4);
sleep(10);
$arr[100000] = 1;
sleep(10);

Now run it and monitor its memory usage.

In the first ten seconds, the program reserves memory for a small array.

In the next ten seconds, if the array reserves space for the unused indices, the memory usage goes ridiculously high compared to the previous one. If it doesn't, though, the memory used will only grow slightly.

This should give you an idea of the effect of your final program, whether or not using a 2D array is a good idea.

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

Comments

2

Don't worry, it won't make any extra keys. PHP is not like that, even arrays that you think are regular are associative arrays. You can even combine PHP arrays like this:

array(
     1 => 121,
     2 => 2112,
     'stuff' => array('morestuff'),
     'foo' => 1231
)

With PHP its very comfortable which can be good and bad also.

Comments

0

It doesn't seem like it will allocate a placeholder or use any memory for the unused keys, based on Doug T.'s response. Hope this helps!

Comments

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.