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

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. There is however, nothing wrong with it.

Cheers - L~R

  • Comment on Re: Re: Re: Matching First Character of Strings Efficiently

Replies are listed 'Best First'.
Re: Re: Re: Re: Matching First Character of Strings Efficiently
by kral (Monk) on Mar 16, 2004 at 16:59 UTC
    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
        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.
        You're right! I have completely misunderstood the test's results. I'm so sorry!
        ----------
        kral
        (sorry for my english)