: I have 2 hashes, %one and %two.
: 
: the ($key, $value) of %one is a span of time.
: 
: I need to compare this span of time over every $key of %two.
: 
: Here's what I have:
: 
: while (($key1, $val1) = each (%one)) {
: 
:       while (($key2, $val2) = each (%two)) {
: 
:               if (($key2 >= $key1) && ($key2 < $val1)) {
:                       
:                       push @match, $val2;
:               }
:       }
: }
: 
: There are 10,000 , 5,000 records in %one and %two, and it keeps timing out.
: ( this is an http-request )
: 
: Is there a more efficient way?

Just off the top of my head, I know that looping over the keys
of a hash is faster than looping over the key/val pairs:

foreach my $key1 ( keys %one ) {
        foreach my $key2 ( keys %two ) {
                if ($key2 >= $key1 and $key2 < $one{$key1}) {
                        push @match, $two{$key2};
                }
        }
}

Also, sorting the keys of %two can give the inner loop an opportunity
place to break off the search early:

foreach my $key1 ( keys %one ) {
        foreach my $key2 ( sort {$a<=>$b} keys %two ) {
                next unless $key2 >= $key1;
                last if $key2 >= $one{$key1};
                push @match, $two{$key2};
        }
}

"last if" will prevent the code from doing any more comparisons
than are necessary.

N.B. This isn't benchmarked, so I don't know how much time it will save,
especially netted against the sort. I'm sure people who actually took an
algorithms class will come up with something better. ;)

-- tdk

Reply via email to