in reply to Returning transliteration from eval
I think your question has been answered, but it is worth pointing out that by using eval you are throwing away all of the performance that was gained by the original move to using tr///.
In almost all cases when the charsets involved in a tr/// are determined at runtime, it is better to eval a subroutine into existsance that perform the required transliteration and then reuse that, rather than re-evaling the tr/// each time you use it.
To emphasis this point, the following benchmark counts the number of 1s in all the integers from 1 to 1 million.
The first method evals a sub into existance to do the counting then calls it 1e6 times. The second uses your method of evaling the entire counting expression 1 million times.
The results show that your method takes 65x longer.
#! perl -slw use strict; use Benchmark qw[ cmpthese ]; cmpthese -1, { one_eval => q[ my $t = 1; eval qq[ sub count { \$_[0] =~ tr[$t][$t] } ]; my $c = 0; $c += count( $_ ) for 1 .. 1e6; print $c; ], many_evals => q[ my $t = 1; my $c = 0; $c += eval qq[ \$_ =~ tr[$t][$t] ] for 1 .. 1e6; print $c; ], }; __END__ C:\test>junk30 600001 600001 (warning: too few iterations for a reliable count) 600001 Subroutine count redefined at (eval 2000016) line 1. 600001 Subroutine count redefined at (eval 2000017) line 1. 600001 Subroutine count redefined at (eval 2000020) line 1. 600001 (warning: too few iterations for a reliable count) s/iter many_evals one_eval many_evals 27.3 -- -98% one_eval 0.416 6451% --
When you use optimisations, it is very important that you understand how they work, otherwise you end up pessimising your code relative to more traditional techniques:
#! perl -slw use strict; use Benchmark qw[ cmpthese ]; cmpthese -1, { one_eval => q[ my $t = 1; eval qq[ sub count { \$_[0] =~ tr[$t][$t] } ]; my $c = 0; $c += count( $_ ) for 1 .. 1e6; print $c; ], many_evals => q[ my $t = 1; my $c = 0; $c += eval qq[ \$_ =~ tr[$t][$t] ] for 1 .. 1e6; print $c; ], loop => q[ my $t = 1; my $c = 0; for my $n ( 1 .. 1e6 ) { ++$c while $n =~ m[$t]g; } print $c; ], }; __END__ C:\test>junk30 600001 600001 600001 (warning: too few iterations for a reliable count) 600001 600001 (warning: too few iterations for a reliable count) 600001 Subroutine count redefined at (eval 2000022) line 1. 600001 Subroutine count redefined at (eval 2000023) line 1. 600001 Subroutine count redefined at (eval 2000026) line 1. 600001 (warning: too few iterations for a reliable count) Rate many_evals loop one_eval many_evals 3.76e-002/s -- -97% -98% loop 1.17/s 3002% -- -52% one_eval 2.41/s 6303% 106% --
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Returning transliteration from eval
by ikegami (Patriarch) on Jan 28, 2011 at 19:47 UTC | |
by BrowserUk (Patriarch) on Jan 28, 2011 at 20:15 UTC |