in reply to Re^2: Common Perl Idioms
in thread Common Perl Idioms

I don't know about any efficiency issues though.

Doesn't look good:

#!perl -l use Benchmark qw(cmpthese); use List::Util 'first'; sub find_first_index_dmq { my $target=shift; push @_,$target; my $i=0; $i++ while $_[$i] ne $target; return $i==$#_ ? undef : $i } sub find_first_index_ihb { my $target=shift; first { $_[$_] eq $target } 0 .. $#_ } # 0 1 2 3 4 5 6 7 8 9 0 1 print 'ihb:',find_first_index_ihb(qw(a b c d e f g h a b c d e)); # 0 1 2 3 4 5 6 7 8 9 0 1 print 'ihb:',find_first_index_ihb(qw(a b c d e f g h b c d e)); # 0 1 2 3 4 5 6 7 8 9 0 1 print 'dmq:',find_first_index_dmq(qw(a b c d e f g h a b c d e)); # 0 1 2 3 4 5 6 7 8 9 0 1 print 'dmq:',find_first_index_dmq(qw(a b c d e f g h b c d e)); cmpthese -1,{ dmq_hit=>'find_first_index_dmq(qw(a b c d e f g h a b c + d e));', dmq_zip=>'find_first_index_dmq(qw(a b c d e f g h q b c + d e));', ihb_hit=>'find_first_index_ihb(qw(a b c d e f g h a b c + d e));', ihb_zip=>'find_first_index_ihb(qw(a b c d e f g h q b c + d e));', }; __END__
Rate ihb_zip ihb_hit dmq_zip dmq_hit ihb_zip 8461/s -- -5% -44% -50% ihb_hit 8869/s 5% -- -42% -47% dmq_zip 15177/s 79% 71% -- -10% dmq_hit 16782/s 98% 89% 11% --

And thats using the XS List::Util implementation from 5.8.2. Theres a lot of overhead in calling the closure, and I think that the range operator isn't lazy in this usage, so it has to manufacture a list of indexes to use.


---
demerphq

    First they ignore you, then they laugh at you, then they fight you, then you win.
    -- Gandhi


Replies are listed 'Best First'.
Re^4: Common Perl Idioms
by BrowserUk (Patriarch) on Jul 24, 2004 at 03:35 UTC

    sub firstIdx { $_[ $_ ] eq $_[ 0 ] and return --$_ for 1 .. @_; return; }

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algoritm, algorithm on the code side." - tachyon