sunshine_august has asked for the wisdom of the Perl Monks concerning the following question:
I have a subroutin, which will return a scalar variable to its caller, but there may be several M bytes contained in the scalar variable, should I return the reference of this scalar variable or return the bare scalar variable for efficiency?
I write a benchmark, it shows that the reference edition is more efficient, but is that true? Following is my benchmark code:
here is the result:#!/usr/bin/perl use strict; use warnings; use Benchmark qw(:all); sub caller_scalar { my $s = stub_scalar(); } sub caller_ref { my $s = stub_ref(); } sub stub_scalar { my $string = 'aaaaaaaaaaaaaaaaaaaaaaaa' x 1000000; return $string } sub stub_ref { my $string = 'aaaaaaaaaaaaaaaaaaaaaaaa' x 1000000; return \$string } cmpthese( 1000, { 'ref' => \&caller_ref, 'scalar' => \&caller_scalar, } );
Rate scalar ref scalar 10.9/s -- -20% ref 13.5/s 24% --
when Perl returns a scalar, does it just return the address of the scalar, or also copy the content of the scalar to the caller?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Does the reference of a scalar more efficient than scalar?
by AnomalousMonk (Archbishop) on Dec 11, 2008 at 10:09 UTC | |
by Tanktalus (Canon) on Dec 11, 2008 at 17:02 UTC | |
|
Re: Does the reference of a scalar more efficient than scalar?
by ccn (Vicar) on Dec 11, 2008 at 09:24 UTC |