Is perl really that slow?

Adam (whose weblog requires I log in to leave comments directly) href="http://adammonsen.com/blog/index.php/2005/08/20/factorial_challenge_python_perl_ruby_and">notices
that python and ruby’s performance seem great while C is (naturally)
very fast. Perl is in the mix, too, and he kindly doesn’t tear it
apart though based on the numbers he would seem justified in doing
so. I wondered if perl was realy that slow so I decided to take
a look…

Let’s start with the listing:

#!/usr/bin/perl

# Computes factorial for number passed as first command
# line argument.

use Math::BigInt lib => 'GMP';
$b = Math::BigInt->new([0]);
print $b->bfac(),"n";

This yields some pretty miserable numbers (mine):

bash-2.05b$ time perl facta.pl 40
815915283247897734345611269596115894272000000000

real	0m0.056s
user	0m0.050s
sys	0m0.010s

Yowza! But what if we don’t import the whole 140k Math::BigInt
namespace and new up one of its objects? That brings us a lot closer
to apples and apples…

sub fact {
    if ($_[0] == 0) {
	return 1;
    } else {
	return ($_[0] * fact($_[0] - 1));
    }
}
print fact ([0]);

Show us what you’ve got, Randall!

bash-2.05b$ time perl factp.pl 40
8.15915283247898e+47
real	0m0.003s
user	0m0.000s
sys	0m0.000s

Bitchin! My moral is not “perl is just as fast as ruby or python” –
nor “perl gracefully handles big numbers just like python and ruby”,
because 5.8 doesn’t, though perl 6, which would be the ruby or python
contemporary, may — but that “a huge feature-rich class is usually
slower than a single dedicated routine.”

Leave a Comment