At 12:39 PM 6/6/00 -0400, Drew Taylor wrote:
>Hello,
>
>This doesn't directly relate to mod_perl, but I'd like to make this as
>memory efficient as possible since it runs under mod_perl. :-) 
>
>I have a question about data structures. Currently, I am doing SQL
>queries and returning an array ref and a hash ref. The array is to
>preserve order, and the hash contains various bits of data about that
>particular product ( it could be another hash ref, and often is). After
>getting the two references, I use foreach to loop through the array, and
>within that loop I access various data from the hash where the productID
>is the key. It looks like this:
>
>Common.pm:
>sub getdata {
>   my $AR = [123, 456, 243, ... ]
>   my $HR = { 123 => {foo=>bar, name=>'name', price=>'123'}, ... }
>   return ($AR, $HR);
>}
>
>Otherstuff.pm:
>my ($AR, $HR) = $self->getdata();
>foreach (@{$AR}) {
>   my $name = $HR->{$_}{name};
>   ...
>}

>I would like to return a single data structure, but order IS important
>(hence the current setup). I was thinking of using an array, where each
>element is a hash reference. So I would return something like this:
>
>[ {ID=>123, name=>'name123', foor=>'bar'},  {ID=>321, name=>'name321',
>bar=>'foo'}, ... ]

Well, if the keys are unique, you could just return a hashref, and then
access it using sorted keys:

foreach( sort keys %$HR ) {
        ## insert useful stuff here
}

>Are there any de-referenceing issues (performance wise) that would make
>this less efficient than the 2 structures? TIA for any pointers.

Probably not, except your method takes more mems, since you're returning an
extra array.  'Course, the sort takes mems as well, but not as much as the
extra array.

And, there is the overhead of sorting the keys.

I think an array of hashref's is probably the best bet.  Then you can use
the DBs sort, and just build the array on the fly, once.

For the site I'm working on, I return a reference to a ResultSet object
which through the next() method returns the next row in the result set:

my $account = $dbs->get_account( "123456789" );
my $rs = $account->get_cards;
while( my $unit = $rs->next ) {
        # do something
}

so this enforces the order (due to the order by in the SQL query).  This is
a bit slower, since next() returns allocated objects, but it works.


Cheers!

        -klm.

-------------------------------------------
Ken Miller, Consultant
Shetland Software Services Inc.

Reply via email to