For a long time now I have suspected that calling perl subroutines is slow. And I couldn’t figure out from the language shootout which benchmark tested subroutine calls (did it use to be Ackermann?) so I made up my own benchmark.

Perl in comparison to its closest rival – CPython.

I tested a few things:

First, a loop that does nothing, to see how much is loop overhead

Next a zero parameter function

Then a function called with two integers

And finally, declaring those two integers inline.

I’m assuming that an optimiser doesn’t come along and remove code that does nothing. From the results, it seems like a safe assumption.

And, I’m not running benchmarks multiple times or with many iterations because, frankly, I don’t care that much. I just want to get an idea as to how Perl stacks up.

Python Code

def f1 (): pass def f2 (a, b): pass # return a, b for i in xrange (1, 10000000): pass # f1 # f2(1, 2) # x,y=1,2

Python Results

$ python -V Python 2.6.5 $ time python ./func.py # (pass) real 0m0.722s user 0m0.720s sys 0m0.004s $ time python ./func.py # (x,y = 1,2) real 0m2.030s user 0m2.024s sys 0m0.004s $ time python ./func.py # (f1) real 0m2.265s user 0m2.244s sys 0m0.012s $ time python ./func.py # (f2 - pass) real 0m2.885s user 0m2.880s sys 0m0.004s $ time python ./func.py # (f2 - return a, b) real 0m3.190s user 0m3.144s sys 0m0.012s

Perl Code

sub f1 { } sub f2 { my ( $x , $y ) = @_ ; } for ($i = 0; $i < 10_000_000; ++$i) { 1; # f1(); # f2(1, 2); # my ($x, $y) = (1, 2); }

Perl Results

$ time perl ./func.pl # (1) real 0m0.893s user 0m0.888s sys 0m0.004s $ time perl ./func.pl # (f1) real 0m2.932s user 0m2.924s sys 0m0.004s $ time perl ./func.pl # (f2) real 0m5.607s user 0m5.580s sys 0m0.004s $ time perl ./func.pl # (my ($x, $y) ...) real 0m2.687s user 0m2.672s sys 0m0.008s

Conclusions

A few things jump out at me.

1. 10 million subroutine calls take around a couple of seconds. Would reducing call speed actually affect any real program much?

2. Declaring the variables and assigning the values takes almost as long as the empty function call.

3. Python function calls are faster than perl function calls but it’s not by enough to worry about.

My next post should hopefully clarify why I was thinking about this.