in reply to Re: Whats quicker - passing along as variable to sub, or global var?
in thread Whats quicker - passing along as variable to sub, or global var?

Ok, well both of these have the same affect:
my $string = "foo bar testing"; my $string2 = "foo bar testing"; use Benchmark; use Test; #################### # Test 1 #################### my $start = new Benchmark; Test::testing1($string); print qq|String is now: $string \n|; my $end = new Benchmark; my $diff = timediff($end, $start); print "Time taken was ", timestr($diff, 'all'), " seconds \n\n"; #################### # Test 2 #################### # start timer my $start = new Benchmark; $string2 = Test::testing2($string2); print qq|String2 is now: $string2 \n|; my $end = new Benchmark; my $diff = timediff($end, $start); print "Time taken was ", timestr($diff, 'all'), " seconds \n\n";
However, if I change the $string and $string2 to:

my $string = "sf osfpsid hfosidhf soifh sofihs foishfosihf soifh soifhsofihsfoihs foishf sofhfo ihsf oishfsoifhsf \n" x 1000000;

...then there is quite a considerable difference. The code in Test.pm is as follows:
package Test; use strict; sub testing1 { print "At testing1 \n"; $_[0] =~ s/foo/test/g; } sub testing2 { print "At testing2 \n"; my $string = $_[0]; $string =~ s/foo/test/g; return $string; } 1;
Judging from the above then - I'm guessing just editing $_[0] directly is gonna be the best option for us, as it seems to be a lot quicker.

Cheers

Andy

Replies are listed 'Best First'.
Re^3: Whats quicker - passing along as variable to sub, or global var?
by jpl (Monk) on Apr 08, 2011 at 14:16 UTC

    Devel::NYTProf, available on CPAN, is also your friend here. It does a wonderful job of showing where the time is going. If your subroutine is only a tiny fraction of the total time used, there's not much point in making it uglier to make it faster. If it is a major player, the profiler will point you to the parts that are worth tuning.