Do sparse arrays take up full memory?

I

Ian

I always thought that

my @array;
$array[0] = 1;
$array[99] = 1;

....would only use two array elements' worth of memory. After reading
some of the documentation, I'm not so sure. What's the real answer
please?

Thanks!
Ian.
 
A

Arndt Jonasson

Ian said:
I always thought that

my @array;
$array[0] = 1;
$array[99] = 1;

....would only use two array elements' worth of memory. After reading
some of the documentation, I'm not so sure. What's the real answer
please?

As an experiment, I ran

#! /usr/local/bin/perl

$a[1] = 1;
sleep 10;
$a[10000000] = 1;
sleep 100000;

and used a process monitoring tool to see perl's memory usage. It
jumped from around 2 Meg to 66 Meg, so it seems it does fill in the
intermediate elements.

(This was in perl 5.8.5.)

If you use large sparse arrays a lot, maybe hash tables are better.
 
A

Anno Siegel

Ian said:
I always thought that

my @array;
$array[0] = 1;
$array[99] = 1;

....would only use two array elements' worth of memory. After reading
some of the documentation, I'm not so sure. What's the real answer
please?

An unoccupied element in an array uses one C pointer.

Anno
 
X

xhoster

Ian said:
I always thought that

my @array;
$array[0] = 1;
$array[99] = 1;

....would only use two array elements' worth of memory. After reading
some of the documentation, I'm not so sure. What's the real answer
please?

The "real" answer is that it uses as much memory as it uses.

The fake answer is that generally a sparse array is going to use less
memory than a non-sparse array covering the same range (because the "empty"
elements do take some space, but not as much as a full blown scalar would),
but will take more memory than a hash using stringified numbers as the keys
will take.

Xho
 
I

Ian

OK, thanks for the answers. I was hoping to use arrays for speed in
looking up dated values, so there's still potential to use it as long
as I keep my known dates within some sensible boundaries (e.g. 20000101
and above, and just subtract 20000101 from the integer date each time).

Thanks
Ian.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top