Markus Dehmann said:
Is it preferrable to pass variables by reference, or does the perl
interpreter optimize things so that it's not necessary?
Whether it is preferrable rarely has anything to do with how the
interpreter optimizes things. Preferred code is usually determined more by
things like correctness, intuitiveness, maintainibility, etc.
Micro-optimiztion of your code is extremely context and detail dependent,
so it is hard to make general statements.
In other words, is the 2nd variant of the following two much more
efficient?
$a = "bla";
$a = modify($a);
print $a;
sub modify { my $b = shift; $b =~ s/l/L/; return $b; }
$a = "bla";
modify(\$a);
print $a;
sub modify { my $bRef = shift; $$bRef =~ s/l/L/; }
time perl -le 'foreach(1..1e7) {$a = "bla";$a = modify($a)}; \
sub modify { my $b = shift; $b =~ s/l/L/; return $b; }'
22.640u 0.000s 0:23.24 97.4% 0+0k 0+0io 351pf+0w
time perl -le 'foreach(1..1e7) {$a = "bla";modify(\$a)}; \
sub modify { my $bRef = shift; $$bRef =~ s/l/L/; }'
16.430u 0.000s 0:17.26 95.1% 0+0k 0+0io 352pf+0w
I'd say it is slightly more efficient, not much more efficient. (Of
course, if $a was much larger, this difference could become greater. But
then again, if $a was much larger, just creating $a in the first place
would probably swamp your call involving $a.)
BTW, did you know that perl automatically passes scalars by alias (which
is kind of, but not exactly, like passing by reference) and that if you
wish to avoid copying the way to do it is by not copying elements of @_ in
the first place? (both you're "my $b = shift" and "my $bRef = shift" are
examples of such copying.)
time perl -le 'foreach(1..1e7) {$a = "bla";modify($a)}; \
sub modify { $_[0] =~ s/l/L/; }'
11.520u 0.010s 0:11.60 99.3% 0+0k 0+0io 349pf+0w