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% --
|