http://www.perlmonks.org?node_id=1058941

Recently, I wrote a script for an individual, which is to take three consecutive letter or number from a line of number or string, until the whole line is "taken care of"{ I hope you get that.}. Of course, I rolled out my while loop, with a regex to "pick out" these three consecutive letters like:

... $str .= $1 . $/ while ( $ARGV[0] =~ m/(.{3})/g ); ...
Then, I was told NO, please can you use substr function? Hummm! Ok I will. Though that doesn't come to me naturally. I felt like, why become verbose when you can be simple and "efficient"? So, I did.
... use constant LEN => 3; ... my $offset = 0; my $length = LEN; while ( $_ = substr $ARGV[0], $offset, $length ) { last if length != LEN; $str .= $_ . $/; $offset += $length; } ...
Of course, it worked, and the input is coming directly from the CLI - Command Line Interface. However, I decided on my own to Benchmark these. Though, I know that substr should be faster than regex usage. So, I called up the benchmark module and did this:
#!usr/bin/perl -w use strict; use constant LEN => 3; use Benchmark qw(:all); my $str; my $count = -2; my $re = timethese( $count, { substring => sub { my $offset = 0; my $length = LEN; while ( $_ = substr $ARGV[0], $offset, $length ) { last if length != LEN; $str .= $_ . $/; $offset += $length; } }, regex => sub { $str .= $1 . $/ while ( $ARGV[0] =~ m/(.{3})/g ); } } ); cmpthese($re);
And my result confirmed by pre-informed mind. With this:
Benchmark: running regex, substring for at least 2 CPU seconds... regex: 1 wallclock secs ( 2.09 usr + 0.00 sys = 2.09 CPU) @ 14 +030.14/s (n=29323) substring: 3 wallclock secs ( 2.14 usr + 0.00 sys = 2.14 CPU) @ 23 +225.70/s (n=49703) Rate regex substring regex 14030/s -- -40% substring 23226/s 66% --
Oh! Yea! So, I thought. But somehow, I check the script and and changed this
... $str .= $1 . $/ while ( $ARGV[0] =~ m/(.{3})/g ); ## NOTE the +number 3 ...
to this
... $str .= $1 . $/ while ( $ARGV[0] =~ m/(.{LEN})/g ); ## NOTE 3 +is now LEN ...
Since the constant LEN is 3, then I got this surprise:
Benchmark: running regex, substring for at least 2 CPU seconds... regex: 4 wallclock secs ( 2.72 usr + 0.01 sys = 2.73 CPU) @ 74 +0317.95/s (n=2021068) substring: 2 wallclock secs ( 2.66 usr + 0.02 sys = 2.68 CPU) @ 17 +332.84/s (n=46452) Rate substring regex substring 17333/s -- -98% regex 740318/s 4171% --
Common on?! Is the benchmark module broke or something? lol!!. Or I didn't write the benchmark script well? Anyway like am back in love with simple and precise over verbose. What do you think?
~ zadok_the_priest ~