Then, I tried optimizing it. The following is a regexp version:sub score { my ($word1, $word2) = @_; # return a special value (defined somewhere in the file # if we have an exact match) return $words_equal if ($word1 eq $word2); my @chars1 = split(//, $word1); my @chars2 = split(//, $word2); my $count = 0; foreach $a (@chars1) { foreach $b (@chars2) { if ($a eq $b) { $count++; last; } } } return $count; }
Benchmarking proved that the second version is about 50% slower than the first & simple one.sub score2 { my ($word1, $word2) = @_; return $words_equal if ($word1 eq $word2); my @chars1 = split(//, $word1); my $count = 0; foreach $a (@chars1) { if ($word2 =~ /$a/) { $count++; last; } } return $count; }
In reply to Optimizing a string processing sub by spurperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |