in reply to Re: Matching First Character of Strings Efficiently
in thread Matching First Character of Strings Efficiently

In my precedent message, I proposed a solution that was not considered maybe because it was in a test context. As a newbie in Perl, I would like to know if my solution is good or wrong.
my $fc = substr($str_a,0,1); for my $str_b ( @list ) { next if ord($fc) == ord((split(//, $str_b))[0]); expensive_function ( $str_a, $str_b ); }
Tnx to all. :^)
----------
kral
(sorry for my english)

Replies are listed 'Best First'.
Re: Re: Re: Matching First Character of Strings Efficiently
by Limbic~Region (Chancellor) on Mar 16, 2004 at 15:02 UTC
    kral,
    Actually, I just missed it when I was doing the benchmark. I would give you an award for having the most un-necessary steps. Let me explain why.
    • You use substr to get 1st char even though ord returns numeric value of 1st char
    • You use split to get a list of individual characters and throw them away using a slice
    • You then use ord again for the test
    There is however, nothing wrong with it.

    Cheers - L~R

      You use substr to get 1st char even though ord returns numeric value of 1st char
      You use split to get a list of individual characters and throw them away using a slice
      I don't want to seem obstinate (I'm here for learning), but I made some tests:
      #!/usr/bin/perl -w use strict; use Benchmark qw(:all); my $str_a = "dlajsdlkajslkdjasldjasljdaskjd"; cmpthese( -5, { 'Test1' => sub { ord( $str_a ) }, 'Test2' => sub { ord( ( split ( //, $str_a ) )[0] ) }, 'Test3' => sub { ord( substr $str_a, 0, 1 ) }, } ); __DATA__ Results: Rate Test2 Test3 Test1 Test2 6321/s -- -99% -100% Test3 516114/s 8065% -- -72% Test1 1827646/s 28815% 254% --
      I convene that isn't much readable, but it seems like the ord function works better with only one character as argument.
      Update: I have misunderstood the result, sorry!
      ----------
      kral
      (sorry for my english)
        kral,
        I think you are misreading something. The first test by far surpassed the other two. In the first test you are using a long string, not a single character.

        Additionally, it isn't that ord works better with only one character as an argument - it is that the other two are doing a lot more work. Using substr or split to get the first character is extra operations that are completely un-necessary. The ord function (perldoc -f ord) would work the same if it was a single character or a long string. It is for this reason that the second two tests take more time. They are doing un-necessary work.

        I hope this clears things up - L~R