Tim
Tim

Reputation: 14164

Why does Perl reallocate memory following this pattern?

The memory addresses for anonymous arrays are naturally re-used by perl. As this example shows, they cycle between two addresses for empty arrays:

$ perl -E "say [] for (1..6)"
ARRAY(0x37b23c)
ARRAY(0x37b28c)
ARRAY(0x37b23c)
ARRAY(0x37b28c)
ARRAY(0x37b23c)
ARRAY(0x37b28c)

I came up with some theories on why it couldn't reallocate the memory immediately, when I found that the cycle isn't always two addresses long. The following examples' cycles are 3 and 4.

$ perl -E "say [0] for (1..6)"
ARRAY(0x39b23c)
ARRAY(0x39b2ac)
ARRAY(0x39b28c)
ARRAY(0x39b23c)
ARRAY(0x39b2ac)
ARRAY(0x39b28c)

$ perl -E "say [0,0] for (1..6)"
ARRAY(0x64b23c)
ARRAY(0x64b2cc)
ARRAY(0x64b2ac)
ARRAY(0x64b28c)
ARRAY(0x64b23c)
ARRAY(0x64b2cc)

What causes this peculiarity of memory management?

Upvotes: 5

Views: 197

Answers (2)

Dave Sherohman
Dave Sherohman

Reputation: 46207

Within the set of examples you've given, the number of addresses is not "two, or sometimes more". It's "the number of elements in the anonymous array, plus two". As ikegami said, the SVs go into a pool when freed, so it is to be expected that the addresses will cycle in some fashion, unless a deliberate effort has been made to retrieve them in a random order (which has obviously not been done).

The remaining question, then, is why the length of the cycle is "number of elements + 2". Perhaps it's using one SV for each element of the array, one for the arrayref itself, and one for $_?

Upvotes: 1

ikegami
ikegami

Reputation: 386256

When SVs are freed, the are actually put into a "free" pool. Perhaps the order into which they enter the pool affects the order in which they exit.

Upvotes: 2

Related Questions