Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Print Vs Return In a Subroutine

by JavaFan (Canon)
on Mar 30, 2012 at 09:40 UTC ( #962553=note: print w/replies, xml ) Need Help??

in reply to Print Vs Return In a Subroutine

print prints its argument(s) to the current filehandle. return returns its argument(s) to the caller of the sub.

The latter is likely to be faster. But they're doing to totally different things, so it's comparing apples with manholes.

Replies are listed 'Best First'.
Re^2: Print Vs Return In a Subroutine
by aaron_baugher (Curate) on Mar 30, 2012 at 23:13 UTC

    My guess was that the original poster was trying to ask if it's faster to print within a subroutine or to return a value and then print it. My benchmark says that it's considerably faster to go ahead and print something right away, than to return it and print it. I suppose that's because calling the subroutine in void context allows some work to be optimized away. Of course, we're still comparing two things that are extremely fast, likely faster than almost anything else in a slow program, so it's unlikely that "optimizing" in this way would ever gain anything noticeable in a real-world situation.

    bannor:~/work/perl/monks$ cat #!/usr/bin/env perl use Modern::Perl; use Benchmark qw(:all); cmpthese( 10_000_000, { 'return it' => \&returnit, 'print it' => \&printit, }); # printing to STDERR so I can redirect to /dev/null # and still see the benchmark results sub returnit { print STDERR _returnit(); } sub _returnit { 'foo'; } sub printit { _printit(); } sub _printit { print STDERR 'foo'; } bannor:~/work/perl/monks$ perl 2>/dev/null Rate return it print it return it 1298701/s -- -24% print it 1703578/s 31% --

    Aaron B.
    My Woefully Neglected Blog, where I occasionally mention Perl.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://962553]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2018-06-25 06:40 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.