Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a significant performance penalty for calling a subroutine vs inline code?

Old school question - I don't know how efficient the running of Perl is.

I have a group of if/elsif/else statements that process lines of data for different data types that come in the report. I find it easier to read and look at the code if I use subroutine calls instead of variable sized chunks of inline code.

Some older languages had significant penalties in handling the calls so that is was faster to include short routines inline rather than call them. I do not need to pass variables with the call. The line being read has all the data and the significant items are put in variables to be processed later.

Probably not a critical bit of knowledge to have but I try to make my programs efficient and be readable. I already have the chain of ifs so that the most common ones are checked first.

I have written the code inline. I have no way to actually measure how fast it runs. Since it processes things every 15 minutes, I don't want to tie up the files anymore than necessary.

like image 621
Bill Avatar asked Sep 02 '25 10:09

Bill


1 Answers

Perl sub calls have a lot more overhead than function calls in most programming languages, however it's still a relatively small amount of overhead compared to things like file IO, network accesses, etc. Unless you're calling a function many thousands of times, there's going to be little advantage to inlining it.

One thing you mentioned stands out to me:

I do not need to pass variables with the call.

This actually gives you a significant optimization possibility.

Instead of calling your function which handles the line as foo(), call it as &foo (with an ampersand and no parentheses). When a function is called in that way, this is a signal to Perl that the function takes no parameters, so Perl will avoid setting up a new @_ array as part of the call. This saves a bit of overhead.

(A side-effect is that the function will now be able to see its caller's @_ array!)

like image 196
tobyink Avatar answered Sep 04 '25 03:09

tobyink