h2 has asked for the wisdom of the Perl Monks concerning the following question:
While getting to that point of a project where optimizing and reviewing my Perl chops begins to seem like a good idea, i decided to check on some assumptions I'd made. Well, ok, not assumptions, I was following what basically most articles on the topic of passing by reference or by copy seem to say, and which I'd, sadly, followed without verifying the murky depths of mythology myself.
This post helped me in my path, and of course, reminded me of the vast pool of things I don't know: Performance issues with subroutines/methods
So I decided to test it, sure in my faith, for faith is what it turns out to be, that of course, passing by reference must always be fast than passing copies, since, well, Perl doesn't have to work much to use a references, but it has todo all kinds of work when it creates copies.
So I tested it:
use strict; use warnings; use Benchmark qw(:all); my @a = ( 'a','b','c','d','e','g','h', 'a','b','c','d','e','g','h', 'a +','b','c','d','e','g','h', 'a','b','c','d','e','g','h', 'a','b','c',' +d','e','g','h', 'a','b','c','d','e','g','h', 'a','b','c','d','e','g', +'h', 'a','b','c','d','e','g','h', 'a','b','c','d','e','g','h', 'a','b +','c','d','e','g','h', ); my $a_ref = [ 'a','b','c','d','e','g','h', 'a','b','c','d','e','g','h' +, 'a','b','c','d','e','g','h', 'a','b','c','d','e','g','h', 'a','b',' +c','d','e','g','h', 'a','b','c','d','e','g','h', 'a','b','c','d','e', +'g','h', 'a','b','c','d','e','g','h', 'a','b','c','d','e','g','h', 'a +','b','c','d','e','g','h', ]; cmpthese(-2, { 'a copy' => sub { my @b = a_copy(@a); }, 'a ref 1' => sub { my $b = a_ref_1(\@a); }, 'a ref 2' => sub { my $b = a_ref_2(\@a); }, 'a ref 3' => sub { my $b = a_ref_1($a_ref); }, 'a ref 4' => sub { my $b = a_ref_2($a_ref); }, }); sub a_copy { my (@a) = @_; return @a; } sub a_ref_1 { my ($a) = @_; return $a; } sub a_ref_2 { return $_[0]; }
Rate a copy a ref 1 a ref 3 a ref 2 a ref 4 a copy 171189/s -- -97% -97% -97% -98% a ref 1 5073751/s 2864% -- -15% -21% -35% a ref 3 5946679/s 3374% 17% -- -7% -23% a ref 2 6408282/s 3643% 26% 8% -- -17% a ref 4 7753141/s 4429% 53% 30% 21% --
Update:
Delete this if needed, I was just misreading, badly, some results, and the question has no relevance and is only a warning to others that sometimes it's good to step away from the keyboard for a few days when you start making mistakes this bad. My apologies to the monks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: A matter of sub pass by reference or copy
by choroba (Cardinal) on Mar 13, 2021 at 20:29 UTC | |
by h2 (Beadle) on Mar 13, 2021 at 20:33 UTC | |
by kcott (Archbishop) on Mar 14, 2021 at 09:48 UTC | |
|
Re: A matter of sub pass by reference or copy
by Anonymous Monk on Mar 14, 2021 at 20:12 UTC |