Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Re: Re: Re: Matching First Character of Strings Efficiently

by kral (Monk)
on Mar 16, 2004 at 16:59 UTC ( [id://337058]=note: print w/replies, xml ) Need Help??


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

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)

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Matching First Character of Strings Efficiently
by Limbic~Region (Chancellor) on Mar 16, 2004 at 17:18 UTC
    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)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://337058]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (None)
    As of 2024-04-25 00:02 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found