Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Print Vs Return In a Subroutine

by remya (Initiate)
on Mar 30, 2012 at 09:36 UTC ( #962552=perlquestion: print w/replies, xml ) Need Help??
remya has asked for the wisdom of the Perl Monks concerning the following question:

Hi, What's the difference between "print" & "return" in a sub. Will this improve any execution speed.
$blocks{listing_row} = $lists; &set_blocks(\$view, %blocks); return $view;
$blocks{listing_row} = $lists; &set_blocks(\$view, %blocks); print $view;
Thanks in advance..

Replies are listed 'Best First'.
Re: Print Vs Return In a Subroutine
by JavaFan (Canon) on Mar 30, 2012 at 09:40 UTC
    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.

      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.

Re: Print Vs Return In a Subroutine
by bart (Canon) on Mar 30, 2012 at 10:40 UTC
    You're micro-optimizing. Stop it.

    Just make your code work, and when you think it woks too slow, benchmark the likely culprits and improve those, if necessary.

    With Time::HiRes you can get the current time in microseconds, so you can measure quite precisely how long a piece of code takes.

      Agreed, premature optimizing is a bad thing.

      Also in the not recommended category is trying to write your own profiler by peppering your code with calls to Time::HiRes::time. Much better to run the code through a proper profiler such as Devel::NYTProf, that will do a much better job, will profile everything including the stuff you did not think was a bottleneck, and will give you a nicely formatted report to look at.

Re: Print Vs Return In a Subroutine
by marto (Bishop) on Mar 30, 2012 at 09:43 UTC

    print will print the value of $view while return returns from the subroutine with the value of $view. They don't do the same thing so you need to think about what you're trying to achieve.

Re: Print Vs Return In a Subroutine
by pklausner (Scribe) on Mar 30, 2012 at 12:37 UTC
    In dubio pro reo I assume the scenario is:
    You need to print a lot of stuff to stdout (screen, file, http pipeline...). You can print immediately. Or return strings up the caller chain where they get printed.
    Q: At which size would you see an performance impact?
    A: I guess bart has it right: "You're micro-optimizing. Stop it."

      Considering nowadays cpu`s and amount of ram, I agree that microptimization is useless.

Re: Print Vs Return In a Subroutine
by tobyink (Abbot) on Mar 30, 2012 at 13:41 UTC

    As others have said, two very different things.

    However, perhaps it's worth mentioning here Capture::Attribute which allows subs to declare that the stuff they print should be returned instead. I wrote it about a month ago as a bit of an experiment, and while it's probably not a great idea for code you actually want to be portable and reliable, it can be quite nice for quick scripts you want to write, run once, and then forget about.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: Print Vs Return In a Subroutine
by heatblazer (Scribe) on Mar 30, 2012 at 11:01 UTC

    I am learning perl recently, but I don`t think that there is some common in statemetns like:

    return $someval; print $someval;

    They are both doing a different things, however, it`s a bit strange since Larry says that actually return can be omitted so the statement:

    sub a { print $variable; } sub b { $variable; }

    supposed to have a dafault return statement so I am not sure if sub a is actually returning a print with a parameter or not. Well, as a former C user, I am returning a strings with :

    sub a { return sprintf("%s", $_[0]); }

    for example... but it`s Perl... there is more than 1 way to do it.

      print and return do completely different things. By default the return value of a perl subrouting is the return value of last evaluated statement. The return value of the print statement is "1" (if it succeded, which is likely always) and the return value of return statement ist the variable you passed to it (or undef if nothing has been passed).

      Take a look at this code:

      #perl my $variable = 234; sub ax { print $variable; print "\n"; } sub bx { $variable; } my $return_val_a = ax(); print "a - [$return_val_a]\n"; my $return_val_b = bx(); print "b - [$return_val_b]\n";
      This will produce this output:
      234 a - [1] b - [234]
      where you can see the difference a() returns one and b() returns the valus of the variable.

        No offense here but in that example I don`t see the point in return/print issue the author of the node asked. I am new to Perl, but as far as I got it the return statement of ax() function you defined is returning 1 because of the successful printing, while bx() just returns a variable content. If print is a function then calling it from another function is the same as calling sprintf... which one of them is better, that I don`t know. Since it`s more than 1 way to do it, I think the owner of this node must choose for him/herself.

      sub a { return sprintf("%s", $_[0]); }
      Calling sprintf() while legal, is not necessary. printing a string to another hunk of memory and returning that is an unnecessary step. There are some uses of sprintf() in Perl, but they are very, very rare.
      return $_[0]; return "this is string $some_var";
Re: Print Vs Return In a Subroutine
by Anonymous Monk on Apr 01, 2012 at 01:11 UTC

    Printing to screen will be the slowest

    Printing to file will be faster than printing to screen, but slower than returning

    Returning will be the fastest , unless you hit the memory limit and move into swap memory

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://962552]
Approved by Corion
Front-paged by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2017-12-13 09:29 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (351 votes). Check out past polls.