Home > perl, Programming, Uncategorized > Perl study note: why using references in functions is the preferred way (mostly)

Perl study note: why using references in functions is the preferred way (mostly)

Using references in Perl has a big advantage over the traditional passing-value way in performance. The reason is simple – no copying is performed when parameters are passed as references to functions. Below is the code I used to test on my Acer AOD 255 netbook:

#!/usr/bin/perl
use Time::Local;
use POSIX qw/strftime/;

sub d {
	my $msg=shift;
	print strftime("[%m/%d/%Y %H:%M:%S] ", localtime(time)).$msg."\n";
}

sub trim_ref {
	my $ref=shift;
	$$ref =~ s/(^\s+|\s+$)//g;
}

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

print "Purpose of this program is to illustrate the advantage of using
references in perl functions. Please note the traditional way might take a while
to finish.\n";


d('running traditional way');

my $str="   this   ";
my $dest;
for my $i (1..1_000_000) {
	$dest=trim($str);
}
d('traditional way done');

my $str2="   that   ";
d('using reference method');
for my $j (1..1_000_000) {
	trim_ref(\$str2);
}
d('ref. done');


Result:
...
[02/26/2011 18:37:43] running traditional way
[02/26/2011 18:37:59] traditional way done
[02/26/2011 18:37:59] using reference method
[02/26/2011 18:38:06] ref. done

The reference way (7 seconds) clearly beat the value-passed way (16 seconds). But this conclusion doesn’t mean passing by reference is always the best way especially when modifying the arguments passed is not desired.

Advertisements
  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: