Is Python slower than Java/C#? [closed]
Asked Answered
A

13

75

Is Python slower than Java/C#?

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

Here is a project that optimizes CPython: unladen-swallow

Artieartifact answered 23/3, 2009 at 10:26 Comment(16)
you know, you really should provide evidence of this...Deglutition
Indeed - at least a test case would help us to reason about it.Hypotonic
furryland.org/~mikec/benchArtieartifact
blog.dhananjaynene.com/2008/07/…Artieartifact
@rajKumar: Please update the question with additional facts -- do not put important information into comments.Titanium
why would you close this, i don't see this as subjective or argumentive. there should be this much flexibility in questions at least!Wundt
on the grounds that as it stands it's not a real question - not enough dataDeglutition
@annakata: There's some data that Python can be slow. It's demonstrably slower than C#. When it comes to Java, this is debatable; there's lot's of JIT factors that influence this.Titanium
Is this a question about run-time or development time? Are you asking if Python are slower to run or are slower to develop?Titanium
guido says sometimes: python focus on fast development - not on fast runtime. you should be able to code skripts as simple and fast as possible.Siblee
@rajKumar: Please, change title of the question to be more neutral and specific.Withe
And what implementation of Python? CPython is only one, there is jython and IronPython as well.Adan
¡¿Offensive?! Why would someone mark that question as offensive?Nostradamus
Slower? Slower for what? It depends on what libraries are you using, as a lot of them are C compiled, specially the number intensive libraries.Imprint
Speed is subjective. What kind of speed are we talking about here? For example, if you are referring to using the CPU cores, then obviously no variant of Python is able to get rid of GIL except Jython - this factor does affect the speed.Edva
It depends on what do u want do with python.Nonpareil
T
125

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 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++.

Titanium answered 23/3, 2009 at 11:25 Comment(16)
"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?Decapolis
I think you need to replace C# with C++ in your post, as C# is not mentioned in the Quesioners link.Marpet
IronPython is not interpreted is just in time compiled to native code, just like C# is ... or Java.Adna
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.Indecency
@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.Titanium
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.Halfblood
@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.Titanium
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#)Geer
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)?Candescent
@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.Titanium
@S.Lott: Alrighty. But then your answer should instead be a comment. ;)Candescent
@user359996: I don't get your comment. You agreed with "Don't conflate language with runtime". Isn't that the point? The question is fatally flawed. One could either assume some kind of "almost always means" or one could clarify. Or one could indicate that the question is fatally flawed and senseless as asked. While "almost always means" is completely useless; and clarification is always useful, there is often a middle ground. And that is to answer a closely-related question without waiting to clarify the vagueness of the question.Titanium
@S.Lott: I said, "Don't conflate a casually worded question with its literal meaning". You replied, "A casually-worded question needs to be clarified until it has a meaning". As such, if this was a casually worded question, you should agree it requires clarification. I assert it was indeed such a question, and moreover that clarification should be sought in the comments, thus my reply that "your answer should instead be a comment."Candescent
@user359996: Good point. No opportunity to add the necessary middle ground. No alternative. All or nothing based on the original comment and nothing else. Thanks for pointing that out.Titanium
@DhananjayNene referred answers here that say exact opposite of what you mentioned.Fortitude
I thought Python was implementation defined? So all "Python implementations" are really a lie, and are really separate languages that try to emulate Python. ; )Battery
O
62

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.

Olivenite answered 23/3, 2009 at 11:30 Comment(1)
I don't think any idiot can do it. It takes a very special kind of idiot :)Le
S
40

As mentioned in the other answers this depends on the run-time system as well as the task at hand. So the standard (C)Python is not necessarily slower than Java or C#. Some of its modules are implemented in C. Thus combining speed of a native implementation with Python's language.

We did a small experiment: We compared the execution time of a Factorial computation in different languages. The test was actually intended to evaluate the performance of arbitrary-precision integers implementations.

testee. language arbitrary-precision integers run-time

     1. Java     java.math.BigInteger         JRE 6.13
     2. .NET     System.Numerics.BigInteger   MS CLR 4.0
     3. Python   long                         Active Python 2.6.2.2
     4. Squeak   BigInt                       Squeak 3.10.2
     5. .NET     Mono.Math.BigInteger         MS CLR 4.0

results:

                 1)         2)       3)       4)        5)
   10.000!      343 ms    137 ms    91 ms  1.200 ms    169 ms
   20.000!    1.480 ms    569 ms   372 ms  1.457 ms    701 ms
   30.000!    3.424 ms  1.243 ms   836 ms  3.360 ms  1.675 ms
   40.000!    6.340 ms  2.101 ms 1.975 ms  6.738 ms  3.042 ms
   50.000!   10.493 ms  3.763 ms 3.658 ms 10.019 ms  5.242 ms
   60.000!   15.586 ms  7.683 ms 5.788 ms 14.241 ms 10.000 ms

alt text
(source: mycsharp.de)

The bar chart shows the results. Python is the clear winner. As far as I know Python uses the Karatsuba-algorithm to multiply large integers, which explains the speed.

Besides, Python's "arbitrary-precision integers"-type is the built-in long. Hence you don't even need special type handling which is required for Java's BigInteger-class.

Sausage answered 24/7, 2009 at 13:13 Comment(6)
and what about these comparisons? IMHO, They look more persuasive than yours. shootout.alioth.debian.org/gp4/… and shootout.alioth.debian.org/gp4/…Historic
@Comptrol Those are out-of-date look here - shootout.alioth.debian.org/u32q/… and here shootout.alioth.debian.org/u32q/…Rugging
think about why those very clever Haskell implementors called their benchmark suite NoFib dcs.gla.ac.uk/fp/software/ghc/nofib.htmlRugging
@Sausage 343 ms 137 ms 91 ms 1.200 ms 169 ms are these values decimals ? 0.343 0.137?Homograph
@Homograph No 1.200ms => 1200ms. Unfortunately, I no longer have the source of the chart to fix this.Sausage
If I had to guess, I'd say the jvm example wasn't benchmarked correctly, unless you're saying there's a special case to calculating 10! in Java...Monarchy
P
32

Simply - Python is slow.

No matter what interpreter (currently available) you use, it is slower than Java and C. In various benchmarks, its slower than Ruby and PHP. Do not depend on other's answers, check and verify yourself.

http://benchmarksgame.alioth.debian.org/u64q/benchmark.php?test=all&lang=python3&lang2=java&data=u64q

Personally I do not think, there is much serious contribution and development done on getting python faster. Since the productivity is good in python and it solves some of problem straight forward, speed/performance is not taken seriously. There are some architecture issues too preventing Python getting performance tweaks.

Disclaimer - This answer probably will hurt Python lovers. I too am Python developer, loves developing webapps in Django/Flask/Pyramid rather than Spring (Java). But I see practically in my work and experience, how Python is slower. The speed is not always my priority. But I do stand with them, who says Python Interpreter should get oiling and greasing or total engine change to at least stand in marathon. It's a mainstream programming language.

Photomultiplier answered 22/7, 2013 at 15:8 Comment(3)
Developer time is more valuable.Muraida
Could you give a summary of what some of these architecture issues are?Prophylaxis
Obvious fews - GIL and single CPU restriction. For experiment, create realtime messaging server on Websocket (JSON payload) using Tornado, and try benchmarking how much message over how many connections it can handle. Write same stuff in Golang, and get ~xNumCPU performance. Scaling from single process to multi processe (in tornado python) will take a huge step in development, but that is far better when done in Golang or even Java (apart from noisy java library issues). What I am telling here is not theory, but what we faced in practical.Photomultiplier
H
16

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.

Hypotonic answered 23/3, 2009 at 10:30 Comment(2)
please check this url blog.dhananjaynene.com/2008/07/…Artieartifact
There is also a branch to move Python to llvm: code.google.com/p/unladen-swallow/wiki/ProjectPlan.Parthena
I
15

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.

Indecency answered 23/3, 2009 at 12:19 Comment(1)
"due to fewer lines of code to write and maintain" - maintain part is mostly hogwash. As your project grows, you will gawk at how tough it is to fix bugs in python. Moreover, it is often insanely hard to read to read python code if people go about compacting stuffMorten
N
10

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
Nostradamus answered 23/3, 2009 at 11:47 Comment(3)
Unless you can provide evidence or reasoning why the "pythonic" version would be about 400 times faster, it's pretty irrelevant.Halfblood
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.Rhnegative
@MichaelBorgwardt the lazy evaluation of zip could really turn the code 400 times faster for big arrays. maybe moreMatriarchy
P
6

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.

Parthena answered 23/3, 2009 at 13:53 Comment(0)
B
5

It doesn't have anything to do with the languages themselves, it's just the fact that java implementation 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 implementation just recently implemented eg threaded dispatch in its interpreter which gave it performance 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.

Biofeedback answered 23/3, 2009 at 13:30 Comment(0)
C
3

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.

Caracalla answered 23/3, 2009 at 10:33 Comment(0)
D
3

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.

Destinydestitute answered 26/4, 2009 at 16:55 Comment(0)
R
3

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#.

Rudolphrudwik answered 22/7, 2009 at 12:58 Comment(1)
That link appears to be dead :-(Handoff
M
1

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.

Marietta answered 23/3, 2009 at 13:4 Comment(4)
Hang on. CPython uses reference counting. Any code that requires that is unlikely to run well multi-core.Olivenite
I was thinking more along the lines of 'multiprocessing' in the stdlib.Marietta
Remember, remember, The Python's GIL.Imprint
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.Longitude

© 2022 - 2024 — McMap. All rights reserved.