in reply to Re: Speeding up a Perl code. Can it be faster?
in thread Speeding up a Perl code. Can it be faster?
This is 6x faster than your original and 50% faster than your latest (and a whole lot more readable to boot):
use strict; use warnings; use Data::Dump qw[ pp ]; use Benchmark qw[ cmpthese ]; my $match_list = 'a/ere,b/ere,c/ere,d/ere,e/ere,f/ere,g/ere,h/ere'; my @markup = ( 'TY:' . 'X{a} X{b} X{c} X{d} X{e} X{f} X{g} X{h} + ' x 100 ) x 3; my @attrs = ( 'TY a=alpha b=bravo c=charlie d=delta e=echo f=fox +trot g=golf h=hotel' ) x 3; my $tag = 'TY'; my $iters = $ARGV[ 0 ] // -1; sub buk { my %xlist = map split( m'/', $_ ), split ',', $match_list; $attrs[ 0 ] =~ s[^$tag ][]; for( split m' ', $attrs[ 0 ] ) { my( $name, $value ) = split '='; ( defined $xlist{ $name } && $markup[ 0 ] =~ s[X\{$name\}][$va +lue]g ) or $markup[ 0 ] = '', last; undef $xlist{ $name }; } $iters == 1 and print "0:$markup[ 0 ]\n" } sub first_draft { my %xlist = map{ split m[/], $_, 2 } grep{ m[/] } split ',', $mat +ch_list; $attrs[ 1 ] =~ s[\A$tag ][]; # clean up my @attr = $attrs[ 1 ] =~ m[(?:\A| )(.+?)(?=(?: \w+=|\z))]g; for( @attr ) { my( $name, $value ) = split '=', $_; # only one attribute of the same name is allowed. if( exists $xlist{ $name } && defined $xlist{ $name } ) { $xlist{ $name } = undef; # this exists now $markup[ 1 ] =~ s[X\{$name\}][$value]g; } else { # fails get nothing and end. $markup[ 1 ] = ''; last; } } $iters == 1 and print "1:$markup[ 1 ]\n" } sub forth_draft { my %xlist = map{ split('\/', $_) } split(',', $match_list); $attrs[ 2 ] =~ s/\A$tag //; # clean up for (split (' (?=\w+\=)', $attrs[ 2 ])) { my ($name, $value) = split('='); # little more golfing action (defined $xlist{$name} && $markup[ 2 ] =~ s/X\{$name\}/$value/g) ? $xlist{$name} = undef # this exists now : $markup[ 2 ] = '' if $markup[ 2 ]; # do this and let it run th +rough, faster. last if !$markup[ 2 ]; # with out this it drops speed now? } $iters == 1 and print "2:$markup[ 2 ]\n" } cmpthese( $iters, { 'first_draft' => \&first_draft, 'forth_draft' => \&forth_draft, buk => \&buk, } ); __END__ C:\test>junk -1 Rate first_draft forth_draft buk first_draft 4640/s -- -79% -86% forth_draft 22226/s 379% -- -33% buk 33339/s 619% 50% --
|
|---|