Reputation: 280
I am new to Perl 5 and so far I understand that subroutines are good for code reuse and breaking long procedural scripts into shorter and readable fragments. What I wanted to know is that are there any performance benefits that come with using subroutines? Do they make the code to execute faster?
Take a look at the following snippets;
#!/usr/bin/perl
print "Who is the fastest?\n";
compared to this one;
#!/usr/bin/perl
# defining subroutine
sub speed_test {
print "Who is the fastest?\n";
}
# calling subroutine ;
speed_test();
Upvotes: 1
Views: 363
Reputation: 46197
The performance benefit of subroutines is that, used proficiently, they allow developers to write, test, and release code faster.
The resulting code does not run faster, but that's OK, because it's not the 1960s any more. These days, hardware is cheap and programmers are expensive. Hiring a second programmer to speed up slow code production costs orders of magnitude more than buying a second machine (or a higher-powered machine) to speed up slow code execution.
Also, as I note with just about every "how can I micro-optimize Perl code?" question, Perl is not a high-performance language, period. Never has been, almost certainly never will be. That's not what it's designed for. Perl is optimized for speed of development, not speed of execution.
If saving a microsecond here and a microsecond there actually matters to your use case (which it almost certainly doesn't), then you will get far greater speed benefits by switching to a lower-level, higher-performance language than you will get by anything you might do differently in Perl.
Upvotes: 6
Reputation: 2341
There is no performance benefit in using subroutines. Actually there is a performance penalty for using them. That is why in highly speed-optimized code subroutines are sometimes "inlined".
But the root of all evil in software development is premature code optimization. Writing code that does not use subroutines/methods to delegate different tasks is way worse on the long run.
Any code block that exceeds 10 (or maybe 25? or 50?) lines usually has to be split. The limit depends on the people you ask.
Upvotes: 4