Monthly Archives: August 2009

Perl: hash, determining memory usage

I’ve done this test many times (and I always forgot what the result was).

This is just a simple test, so don’t expect a fancy or in-depth discussion. I just want to check if how much memory can a hash consume, given its values are undef, again, a very rough estimate.

With a million keys of 10 digit numbers:

perl -e ‘my $x = {}; for (my $i = 0; $i < 1_000_000; $i++) { my $key = sprintf(“%010d”, $i); $x->{$key} = undef;}; print “sleeping\n”; sleep 10;’

It consumed about 124MB of memory.

Made some change with the title, what I wrote was quite confusing. Another approach to make it simpler and accurate is to use a CPAN module, Devel::Size

use Devel::Size qw{ total_size };
my $x = {};
for (my $i = 0; $i < 1_000_000; $i++) {
    my $key = sprintf("%010d", $i); $x->{$key} = undef;
print "usage:", total_size($x), " bytes\n";