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

Alternatively, reference my variables external to your code, acting a lot like global variables:

my $oldcontents; # initialize $oldcontents my $newcontents; sub my_test { # read from $oldcontents # write to $newcontents } my_test();
But benchmark, by all means.

  • Comment on Re: Whats quicker - passing along as variable to sub, or global var?
  • Download Code

Replies are listed 'Best First'.
Re^2: Whats quicker - passing along as variable to sub, or global var?
by ultranerds (Hermit) on Apr 08, 2011 at 13:48 UTC
    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

      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.

Re^2: Whats quicker - passing along as variable to sub, or global var?
by ultranerds (Hermit) on Apr 08, 2011 at 13:21 UTC
    Thanks - the problem with that, is we are passing back and forth around other .pm files (for example, View.pm, which actually grabs the contents... then Markups.pm, which process the wiki markups, and then returns back to View.pm, etc)

      You can avoiding copying to/from your my_test() routine. If you must copy to initialize the old content, and to pass back the new content, such is life.