Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Print Vs Return In a Subroutine

by JavaFan (Canon)
on Mar 30, 2012 at 09:40 UTC ( [id://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 962552.pl #!/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 962552.pl 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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://962553]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2024-04-25 17:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found