This is somewhat self-promoting, but as the question is asked with some frequency here and elsewhere, I think this is in order.

Q: How can I find out how much memory my scalar/array/hash/multidimensional data structure uses?
A: Use Devel::Size

Devel::Size is a module designed specifically to figure out how much real memory a variable is using. This counts all the memory, including all of perl's internal bookkeeping and cached memory, not just what you might be able to see from the perl level. (Including things like the memory used for magic, the variable-sized structures that represent scalars of different types, and preallocated extra bits for arrays and hashes)

Here's a quick example of its use, from the docs:

use Devel::Size qw(size total_size); my $size = size("A string"); my @foo = (1, 2, 3, 4, 5); my $other_size = size(\@foo); my $foo = {a => [1, 2, 3], b => {a => [1, 3, 4]} }; my $total_size = total_size($foo);
It does follow references when using the total_size function, and does make sure that no structure is counted more than once, so it's safe to use with self-referential data structures.

At the moment its one failing is that it doesn't handle code refs quite completely (it doesn't trace through the scratchpads) and so will complain if you try it on a code ref, or something that has a code ref. It will do its best, though, and count up the memory that it does know how to find. It also won't trace memory that isn't perl's, for example memory that an external library has allocated for itself.

Thanks are due to kudra who both wrote the docs and prodded this module into existence in the first place.

Disclaimer: I wrote the module, so this isn't exactly an unsolicited testimonial :)


In reply to Finding the size of a variable by Elian

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.