in reply to Re^2: Array or Hash
in thread Array or Hash

Are you sure about that?

Yes. I am very sure.

Unlike C, perl can do sparse arrays without using lots of memory for the empty slots,

No. It cannot.

The second assignment in your example (on a 64-bit system) results is the allocation of 134 megabytes of ram:

$a[0]=1; print total_size( \@a );; 232 $a[1]=1; print total_size( \@a );; 256 $a[2]=1; print total_size( \@a );; 280 $a[10_000_000]=1; print total_size( \@a );; 134217984

To gain a better appreciation for how Perl uses memory, see PerlGuts Illustrated and scan down to the AV heading.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^4: Array or Hash
by chrestomanci (Priest) on Jan 21, 2011 at 16:14 UTC

    Thanks ikegami and BrowserUk I stand corrected.

    I am surprised that perl is inefficient with sparse arrays. I guess that if I need to create one, I should in future use a hash with numbers as the keys.

      I am surprised that perl is inefficient with sparse arrays.

      It's more than a little inaccurate to say that, given that Perl doesn't even attempt to implement sparse arrays.

      You might just as well say that Perl is inefficient at implementing birth control or nuclear fusion :)

      I guess that if I need to create one, I should in future use a hash with numbers as the keys.

      Indeed. If your "array" is likely to be less that 45% full, using a hash with numeric keys will save you memory at the cost of a little speed.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
Re^4: Array or Hash
by ahmad (Hermit) on Jan 21, 2011 at 15:41 UTC

    Can you provide the code of the "total_size" sub?

    As it looks interesting.

      See Devel::Size


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.