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.

UPDATE:
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";

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s