Why is my perl script an order of magnitude faster than the equivalent python code

1.4k Views Asked by At

I've recently taken up Python3 and was stumped by how much slower than other comparable dynamic languages (mainly Perl) it is.

While trying to learn Python I did several online coding challenges and Python would often be at least 10x slower than Perl and use at least 2x the memory.

Researching this curiosity I came across people asking why Python is slower than C/C++, which should be pretty obvious, but not any posts comparing it to other similar languages. There is also this informative but outdated benchmark http://raid6.com.au/~onlyjob/posts/arena/ which confirms it being rather slow.

I am explicity asking about the standard Python implementation and NOT anything like pypy or the likes.

EDIT: The reason I was surprised comes from the results page on codeeval.com. Here are two scripts to capitalize the first character of every word in a line.

Python3 (3.4.3) v1

import sys
import re

def uc(m):
    c = m.group(1)
    return c.upper()

f = open(sys.argv[1], "r")
for line in f:
    print(re.sub(r"\b(\D)", uc, line))

Perl (5.18.2)

use strict;
use warnings "all";

open(my $fh, "<", "$ARGV[0]") or die;
while (<$fh>)
{
    s,\b(\D),uc $1,ge;
    print;
}
close $fh;

As I am not very familiar with Python yet I also tried a different version to see if there was any difference.

Python3 v2:

import sys

f = open(sys.argv[1], "r")
for line in f:
    lst = [word[0].upper() + word[1:] for word in line.split()]
    print(" ".join(lst))

The results are quite different as can be seen in this image: https://i.imgur.com/3wPrFk5.png (results for Python in this image are from the v1, v2 had nearly identical stats (+1 ms execution time, ~same memory usage)

0

There are 0 best solutions below