http://qs1969.pair.com?node_id=327062


in reply to Difference between tr/// and s///?

my day for benchmarking it seems

#!perl-w use Benchmark qw(:all); $toto = 'this+is+my+text'; $count =-5; $results = timethese($count, { 'Translating' => sub { my($copy)=$toto; $copy =~tr/+/ +/; }, 'Substituting' => sub { my($copy)=$toto;$copy =~s/\+/ +/g; }, }, 'none' ); cmpthese( $results ) ; __END__ Yielded: Rate Substituting Translating Substituting 140156/s -- -68% Translating 436379/s 211% --

Another perl function which out performs regex is index(), for checking for exact matches in textual data:

#!perl-w use Benchmark qw(:all); $toto = 'this+is+my+text'; $count =-5; $results = timethese($count, { 'Indexing' => sub { my($copy)=$toto; $index = index($c +opy, 'is');}, 'matching' => sub { my($copy)=$toto;$match if $copy =~ +/is/; }, }, 'none' ); cmpthese( $results ) ; __END__ Gave: Rate matching Indexing matching 552818/s -- -14% Indexing 641382/s 16% --

but obviously there are limitations, with tr// you can't use it on only part of a string and index() only returns the position of the first match of an exact term or character in text data. The extra control and options offered by regex are what make them slower than both these functions in given situations.

Update

As Davido pointed out the original benchmark tests were flawed and have since been adjusted.

You spend twenty years learning the spell that makes nude virgins appear in your bedroom, and then you're so poisoned by quicksilver fumes and half-blind from reading old grimoires that you can't remember what happens next.