Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slow loops in Perl

The following subroutine takes 12 seconds in my computer to execute:

sub trans() {   
    $trans = "";
    foreach $nuc (@array) {
        foreach $k (keys %hash) {
            if ($nuc eq $k) {
                $w = $hash{$k};
                $trans .= $w;
                last;
            }
        }
    }
}

The code continues generating a file with the content of $trans. It takes, as I said, 12 seconds. The problem is that I have to produce 256 output files...... and it takes too long.....

Any idea for optimizing it??

like image 556
user2886545 Avatar asked Nov 07 '13 08:11

user2886545


1 Answers

Why do you loop over every key in the hash just to test whether it equals a known value?

sub trans() {   
    $trans = "";
    for my $nuc (@array) {
        if (exists $hash{$nuc}) {
            $trans .= $hash{$nuc};
        }
    }
    return $trans;
}

But then... why bother testing, either.

sub trans() {   
    $trans = "";
    for my $nuc (@array) {
        $trans .= $hash{$nuc} // "";
    }
    return $trans;
}

And who needs loops anyway?

sub trans() {   
    return join '', map { $hash{$_} // '' } @array;
}
like image 58
Eevee Avatar answered Oct 06 '22 00:10

Eevee