why python is slower than java?

Ian Bicking ianb at colorstudy.com
Fri Nov 5 18:05:07 CET 2004


Maurice LING wrote:
> This may be a dumb thing to ask, but besides the penalty for dynamic 
> typing, is there any other real reasons that Python is slower than Java?

Python is generally late-bound, which means much more happens at runtime 
compared to Java.  For instance, consider accessing an attribute, 
"self.x".  In Java you know what the class is shaped like, exactly. 
Usually this turns into some bytecode like "access the variable of self, 
at offset 3".  I don't know any of the details, but that's the general gist.

Similarly, there's many other optimizations where you can know at 
compile time exactly what functions are called, how variables are 
stored, etc.  Using that information, you can do optimizations like 
inline code.  In the same places in Python, you are typically doing one 
(or several!) hashtable lookups based on the variable or attribute name.

But even in Java there are limits.  Because of interfaces and subclasses 
you can know the shape of self/this, but you can't know the exact shape 
of the objects around you (C++ is more aggressive in this respect, and 
often can determine the exact shape; but in the process it's dangerous 
to put together different pieces of compiled code when they don't know 
about each other, which is why binary interfaces there are fragile). 
Anyway, Java does a lot of the same stuff as Python when the exact type 
is determined at runtime (which is frequently).  This is where JIT comes 
in, doing the optimizations at runtime; it is still limited, as it 
cannot guarantee the type of the objects in the system, but must check 
them each time before using the optimized path.  And, actually, Python 
can do the same sort of things with psyco.  It's still harder in Python, 
and the end result not as effective, but it's one among many tools.

If Java wasn't doing any optimizations, I don't think it would be 
significantly faster than Python.

Also note that Python assimilates external (C, Fortan, etc) libraries 
much better than Java seems to.  In an entire system, Python can easily 
be faster because Java includes many slow libraries (slow compared to 
equivalent libraries available in Python).  E.g., Swing is much slower 
than wxPython.

Anyway, that's my take.  I'm no authority, as I've never seriously used 
Java, and haven't done any tests, nor spent anytime looking at the 
bytecodes, etc.

-- 
Ian Bicking  /  ianb at colorstudy.com  /  http://blog.ianbicking.org



More information about the Python-list mailing list