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

Not sure what you mean?

I meant exactly what I wrote: Passing a string to a function doesn't make a copy. Assigning it to a separate variable does. So

sub f { print $_[0]; }

avoids the copy, whereas

sub f { my $x = $_[0]; # copy created here print $x; }

creates one.

Since it's quite ugly to use $_[NUMBER] all the time, I suggested references instead.

Replies are listed 'Best First'.
Re^4: Whats quicker - passing along as variable to sub, or global var?
by ultranerds (Hermit) on Apr 08, 2011 at 13:50 UTC
    Aaaah ok - missed that reply =) That would explain why testing1() is considerably quicker than testing2() in the below:

    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; }
    Thanks!

    Andy
      Notice that in testing1() you're modifying the original string, so it's very likely the substitution does just plain nothing in all except the very first run.

      In testing2(), you're starting with a new string every time.

      So, that's probably skewing the benchmark.