in reply to Matching First Character of Strings Efficiently

Trade a little setup time for speed in the loop and use a hash?

my @list = ...; my %list; @list{ map{ substr $_, 0, 1 } @list } = (); my $str_a = 'Foo'; my $first_c = substr $str_a, 0, 1; for my $str_b ( @list ) { next if exists $list{ $first_char }; expensive_function($str_a , $str_b); }

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail

Replies are listed 'Best First'.
Re: Re: Matching First Character of Strings Efficiently
by Limbic~Region (Chancellor) on Mar 15, 2004 at 20:16 UTC
    BrowserUk,
    I am very interested to see if this solution has an efficiency breakpoint. It certainly would not be as memory efficient as some of the other solutions, but that was not a requirement - just speed.

    Cheers - L~R

      Sorry Limbic~Region, I got carried away with your "Only modify this line" (and had a brainfart too!).

      There is no point in looping over the array, that's why we put in a hash. It should have looked something like this.

      my @list = ...; my %list; @list{ map{ substr $_, 0, 1 } @list } = (); my $str_a = 'Foo'; expensive_function($str_a , $str_b) unless exists $list{ substr $str_a, 0, 1 };

      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
        BrowserUk,
        Actually, unless I am missing something I can't include this solution at all. The testing to see if the two strings first characters are the same is just the initial test. The expensive_function actually does a futher comparison. I had a brain fart to when reading it.

        Cheers - L~R