views:

3673

answers:

13

is python slower than java/C#?

performance-comparison-c-java-python-ruby-jython-jruby-groovy

Here is a project that optimizes CPython unladen-swallow

A: 

Python is an interpreted language, And Java or C# is complied language.

Anuraj
python can be compiled right
yesraaj
python is a compiled language. no less. It uses byte codes similar to Java and C#.Don't confused "interpreted" with "dynamic".Pyhton is a dynamic language, Java and C# are static languages.
Ber
Don't confuse compiling to bytecode with compiling to native code.
Pete Kirkham
I don't. It is compiling in both cases, for different targets. It is different from interpreting the source code.
Ber
Interpreting byte code is usually faster than "interpreting the source code" (which never happens; everyone interprets some representation of the source code), but that there is a translation to bytecode rather than a structure representing the AST doesn't mean python isn't a interpreted language.
Pete Kirkham
(actually, thinking of it, MSDOS batch files must interpret the source code, because the operation changes if you write to the batch file while the batch file is being interpreted, so there are real interpreted languages, but most general languages interpret a representation)
Pete Kirkham
+6  A: 

As suggested in comments, you should really provide a test case to reason about. Reasons behind performance differences will change depending on the test being executed.

However, I'd suggest that the static vs dynamic nature may well have a lot to do with it. For non-virtual calls, the JIT-compiled C#/Java is extremely cheap as it can be determined accurately at JIT-time. Even virtual calls just involve a single level of redirection. When binding becomes dynamic, there's a wider range of things to consider.

I don't know enough details about Python to claim to understand its exact runtime behaviour, which I suspect may vary with version and implementation too. There is such a thing as "python byte code" which is then executed by a virtual machine - whether this virtual machine actually performs JIT-compilation or not is another matter.

Jon Skeet
please check this url http://blog.dhananjaynene.com/2008/07/performance-comparison-c-java-python-ruby-jython-jruby-groovy/
yesraaj
There is also a branch to move Python to llvm: http://code.google.com/p/unladen-swallow/wiki/ProjectPlan.
Jason Baker
+1  A: 

I think opposite. I can do simple program in Python faster than in Java, and those Python scripts work really fast.

Of course your question without examples is hard to answer. Maybe you have found slow library, bug etc. Give us more details please.

Michał Niklas
+35  A: 

Don't conflate Language and Run-Time.

Python (the language) has many run-time implementations.

  • CPython is usually interpreted, and will be slower than native-code C#. It might be slower than Java, depending on the Java JIT compiler.

  • JYthon is interpreted in the JVM and has the same performance profile as Java.

  • IronPython is relies on the same .NET libraries and IL as C#, so the performance difference will be relatively small.

  • Python can be translated to native code via PyREX, PyToC, and others. In this case, it will generally perform as well as C++. You can -- to an extent -- further optimize C++ and perhaps squeeze out a little bit better performance than unoptimized output from PyREX.

    For more information, see http://arcriley.blogspot.com/2009/03/so-long-pyrex.html

Note that Python (the language) is not slow. Some Python run-times (CPython, for example) will be slower than native-code C++.

S.Lott
"native-code C#"? Isn't C# just compiled down to the .Net CLI and run in the .Net VM (like Java runs in the JVM)? Are you suggesting there's a way to compile C# into straight native code, or are you just talking about the JITing that happens in the .Net VM?
Herms
I think you need to replace C# with C++ in your post, as C# is not mentioned in the Quesioners link.
Martin OConnor
IronPython is not interpreted is just in time compiled to native code, just like C# is ... or Java.
Pop Catalin
Thanks for the additional corrections.
S.Lott
Jython does not have the same performance profile as Java at all. In fact I benchmarked it in the blog post referred to in the question and it is a lot lot slower than java.
Dhananjay Nene
@Dhananjay Nene: the comparison (it appears from other answers) used a literal rewrite of Java in Python, resulting in un-pythonic code that may not be an appropriate comparison between languages.
S.Lott
That's beside the point- the fact is that Jython does NOT even remotely have the performance profile of Java. Whether this is due to the JVM or, the language, or its implementation on the JVM is another matter. To me it looks to be the latter, especially since JRuby seems to be performing on par with the C implementation of Ruby.
Michael Borgwardt
@Michael Borgwardt: That's the usual culprit -- but "benchmarks" which are not Pythonic are not an acceptable comparison. No one tries to add all of Python's dynamic memory management to C programs before they do the comparison to prove that C is faster than CPython.
S.Lott
C# and IronPython run at nowhere near the same speed. This is to be expected; Python is a much higher-level language (also, the IronPython compiler isn't nearly as mature as the C#)
BlueRaja - Danny Pflughoeft
Don't conflate language with runtime, sure, but also don't conflate a casually worded question with its literal meaning. When people ask this sort of question, they __almost always__ mean, *Without unusual effort or cost, will the fastest non-esoteric implementation coupled with a typical runtime environment (which tends to mean a relatively modern Windows or Linux system) tend to be faster for typical development ("typical" depending on context, but usual relating to generic Enterprisey stuff, scripting, and/or web development--and only rarely numerical integration--by average developers)?*
@user359996: "don'e conflate a casually worded question with its literal meaning". Correct. A casually-worded question needs to be **clarified** until it has a meaning. What is "almost always means" is useless for providing an actual, usable answer. "relatively modern Windows or Linux system" are **not** equivalent for certain problem domains, so it can't be assumed, but must be clarified. '"typical" depending on context' is the point. Without context, casually-worded questions can't be answered based on assumptions.
S.Lott
+23  A: 

It is not really correct to ask why Python is slower than Java/C#. How fast is Java? Well, naive interpreters are around ten times slower than optimised compilers. I believe there is a Java bytcode interpreter written in JavaScript - that probably isn't very fast. So, the intended question appears to be "Why is the CPython language system slower than the equivalent Sun, IBM and Oracle JRE and Microsoft .NET runtime?"

I believe the correct answer is non-technical. The fastest Java and .NET runtime are faster because they have large full time technical teams developing them in performance-competitive environment.

Dynamic language systems are easy to implement. Any idiot can do it. I have. Static language systems are more complex to design and implement. A simple static system will tend to run much faster than the equivalent just-working dynamic equivalent. However, it is possible for highly optimised dynamic systems to run almost as fast. I understand some Smalltalk implementation were quite good. An often quoted example of a developed dynamic system is the MIT Lisp Machine.

In addition if the real grunt is being done by library code, then the language system may not matter. Alternatively, the language may encourage (or give time(!)) to develop more efficient algorithms which can easily wipe out constant factor performance differences.

Tom Hawtin - tackline
A very interesting rant! :)
karim79
+5  A: 

What you got there is clear example of writing Java in Python:

 def __init__(self,size):  
     self.first = None  
     last = None  
     for i in range(size):  
         current = Person(i)  
         if self.first == None : self.first = current  
         if last != None :  
             last.next = current  
             current.prev = last  
         last = current  
     self.first.prev = last  
     last.next = self.first

A bit more pythonic:

 def __init__(self,size):  
     chain = [Person(i) for i in range(size)]
     self.first = chain[0]
     chain = zip(chain, chain[1:].append(chain[0]))
     for p,n in chain:
        p.next = n
        n.prev = p
vartec
Unless you can provide evidence or reasoning why the "pythonic" version would be about 400 times faster, it's pretty irrelevant.
Michael Borgwardt
I think it's quite relevant to point out that all that finicky low-level twiddling is likely to be slower than the direct, pythonic approach. However there's an error in the latter -- .append() returns None; vartec may have meant chain[1:]+chain[:1] instead.
Alex Martelli
+7  A: 

It boils down to the fact that the compilation phase has lesser information to work with and hence the runtime needs to do more work in case of duck typed (dynamically typed) languages.

Thus if I am making the method invocation foo.bar(), in case of Java or C++ the invocation to bar can be optimized in the compilation process by discovering the type of "foo" and then directly invoking the method at the memory location where the compiler knows it will be found. Since a python or any other dynamically typed language compiler does not know what type the object foo belongs to, it has to do a type check at runtime and then look up the address of the bar method and then invoke it.

There are other difficulties a python compiler writer struggles with as well, though the one above hopefully adequately gives an indication. So even with the best compiler writers, statically typed languages are likely to perform much better at runtime.

Where dynamically typed languages score are typically in the development time. Due to fewer lines of code to write and maintain, and no compile wait times for developers, the development often goes through much faster.

Dhananjay Nene
duck != dynamic.
Jon Harrop
+1  A: 

I would argue that the ease and simplicity of writing Python code makes it possible to write more complex code; for example, code that takes advantage of multi-core processors. Since per-core performance has been mostly stagnant for the past 5-10 years, I don't think it's clear that Python programs (whether they're running on CPython or something else) are slower in the long run.

DNS
Hang on. CPython uses reference counting. Any code that requires that is unlikely to run well multi-core.
Tom Hawtin - tackline
I was thinking more along the lines of 'multiprocessing' in the stdlib.
DNS
Remember, remember, The Python's GIL.
voyager
For real scale, you need to go to multiple physical machines anyway. For this, there is no option but to use multiple processes. Therefore, just use multiple processes for single machines too, and you will already have a system that can scale even bigger than that single machine if needed, and the host OS will run your subprocesses on all the cores. The GIL is just not that big a deal once multiprocessing is considered at the outset.
cjrh
+2  A: 

It doesn't have anything to do with the languages themselves, it's just the fact that java imlementation and runtime system (JVM) are very high quality, and that lots of resources have been invested in stability, scalability and performance improvements over the years.

Contrast that to the fact that CPython imlenmentation just recently imlemented eg threaded dispatch in its interpreter which gave it perf boost of up to 20% for certain problems. It's not a good thing as it sounds, it is bad because that kind of basic optimization should be there from the day one.

Dev er dev
+3  A: 

I think it's ultimately that Python doesn't go as far as it can with optimizations. Most of the optimization techniques that are common are for static languages. There are optimization techniques for dynamic languages, but the modern ones don't seem to make as much use of them as they could. Steve Yegge has an excellent blog post on the subject.

EDIT: I just wanted to point out that I'm not necessarily stating this to be critical of Python. I prefer simplicity over unnecessary speed any day.

Jason Baker
A: 

Since it's interpreted and not compiled.. it should be slower in execution time.

As a table mentioned in Code Complete (second edition) book, page 600,

C# equals C++ in execution time (1:1). And Python is slower above hundred times than C++ in execution time (>100:1).

And Java is slower than C++ by one time and a half (1.5:1).

These statistics are on average. I don't know who made this study, but seems interesting.

Saleh Al-Zaid
+2  A: 

This type of question can't be answered just by qualitative reasoning, you need good benchmarks to back it up. Here's one set that compare Python 3 vs C# Mono and find Python to be 3 to 300 times slower. The Python vs. Java results are similar. (The usual cautions about interpreting benchmarks apply.)

These benchmarks also report the source code size, and Python was significantly more concise than Java and C#.

Jim Ferrans
+7  A: 
wierob
Comptrol
igouy
@wierob - think about why those very clever Haskell implementors called their benchmark suite NoFib http://www.dcs.gla.ac.uk/fp/software/ghc/nofib.html
igouy