Home > perl, Programming > Interesting results from benchmarking trim “function” in Perl

Interesting results from benchmarking trim “function” in Perl

I’ve been wondering if writing a customer trim function in perl will come with some performance penalty. To satisfy my itchiness, I ran the following three scripts one at a time and use handy command time to get the running times.

cat a.pl

#!/usr/bin/perl
#!/usr/bin/perl
use warnings;
use strict;

sub trim {
	my $str=shift;
	$str =~ s/^\s+|\s+$//g;
	return $str;
}

my $test_str= "  this is a test   ";

my $result;
for my $i (0..1_000_000) {
	my $copy=$test_str;
	$result=trim($copy);
}

——————————
time perl a.pl

real 0m18.451s
user 0m18.417s
sys 0m0.012s

cat b.pl


#!/usr/bin/perl
use warnings;
use strict;

my $test_str= "  this is a test   ";

my ($result,$copy);
for my $i (0..1_000_000) {
	$copy=$test_str;
	$copy =~ s/^\s+|\s+$//g;
	$result=$copy;
}

——————————
time perl b.pl

real 0m13.330s
user 0m13.313s
sys 0m0.000s

By using the regex directly saves the running time by a few seconds. And I continue to break the regex into two as follows:

cat c.pl

#!/usr/bin/perl
use warnings;
use strict;

my $test_str= "  this is a test   ";

my ($result, $copy);
for my $i (0..1_000_000) {
	$copy=$test_str;
	$copy =~ s/^\s+//g;
	$copy =~ s/\s+$//g;
	$result=$copy;
}

——————————
time perl c.pl

real 0m6.534s
user 0m6.524s
sys 0m0.004s

I thought the results from b.pl and c.pl should be pretty close but I was so wrong – it takes only a half of the time to run c.pl when compared to b.pl.

What I learned from the above bench mark tests:
1) Avoid trim “functions” as much as possible
2) Use the double regex method as shown in c.pl instead of one regex
3) Running time can be cut further if it’s known beforehand whether there are trailing spaces (use s/\s+$//g) or leading spaces (use s/^\s+//g) only

Advertisements
Categories: perl, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: