r/AskComputerScience • • May 20 '19

If every language is eventually compiled into the most basic machine instructions then why do languages like C and C++ run faster than Java and Python?

I don’t understand why lower level languages run faster than higher level ones if they are all eventually compiled into machine code.

61 Upvotes

13 comments sorted by

54

u/sepp2k May 20 '19

First of all, you should distinguish between a language and its implementation(s). How and whether code in a language is translated to machine code can and does vary widely between different implementations of a language. For example the Python implementation PyPy has a JIT compiler, but CPython does not.

If every language is eventually compiled into the most basic machine instructions

This isn't true. Not every programming language implementation emits machine code (as mentioned above, CPython doesn't), nor does every language have at least one implementation that does.

Beyond that, it doesn't only matter whether machine code is generated - it also matters which machine code is generated (also when in the case of JITs). For example, a naive compiler for a dynamically typed language might generate type checks for every operations (while a more complex, optimizing compiler still wouldn't be able to avoid doing so in all cases) while a compiler for a completely statically typed language would have no reason to do so. Similarly virtual function calls will necessarily involve extra lookups that can't always be optimized away.

In addition, a language might use big integers as their default integer types, heavily feature reflection, or contain plenty of other features that tend to be costly to implement.

Even among implementations for the same language, performance can differ significantly, so it's not surprising that implementations for different languages with different features and requirements would have even more differences in performance.

And then there's of course the fact that some languages simply have more mature (and thus better optimized) implementations than others based on how long they've been around, how widely they're used, and how much performance is even a priority.

7

u/Klinging-on May 20 '19 edited May 20 '19

What is the logic behind using a slower implementation? Since Python and Java are widely used languages it seems like they'd have the means to make a compiler that optimizes run-time - thus making a higher level language competitive with languages like C and C++ in that regard. Unless there are things unique to these languages that make it harder/impossible to be competitive with lower level languages in run-time.

Edit: /u/frikk answered this question below. The cost of using higher level languages, which allow you to write code more like english, is that they include a bunch of stuff on the backend to make easier expression of logic possible.

10

u/sepp2k May 20 '19

What is the logic behind using a slower implementation?

The slower implementation may have been around longer and tested more widely. It may implement the most current version of the language whereas other implementations may lack behind (for example PyPy currently only supports Python 3.6 whereas the current version is 3.7). It may have additional features (for example if you view "clang with sanitizers enabled" and "clang with sanitizers disabled" as two different implementations of C, the latter will obviously be faster, but there are still good reasons to use the former, at least during development). Or the faster implementation may not even support the platform you're targetting. There's plenty of reasons to use an implementation other than the fastest one.

Additionally which implementation is faster can depend a lot on context. Some implementations may perform better on some programs, but worse on others. And depending on your situation startup time may matter a lot to your or not at all. Likewise on a memory-constrained system you might want to sacrifice speed for memory efficiency whereas you might prefer the speed otherwise.

Unless there are things unique to these languages that make it harder/impossible to be competitive with lower level languages in run-time.

As I've mentioned in my earlier reply, there are plenty of language features that are hard to implement efficiently. Specifically for Python and Java:

Python is dynamically typed, all method calls are virtual, there's plenty of reflection and it uses big integers by default.

Java allows more room for an efficient implementation and the JVM is in fact quite fast (quite a lot faster than the current Python implementations to be sure). Still, Java has virtual-by-default methods and reflection.

Also the memory model of both languages will lead to more heap-allocation and pointer dereferences than in an efficiently programmed C program. And as other people already mentioned, both languages have bounds checks (as do most other languages that aren't C), so that's another factor that may cause some slow down (though I'd imagine the other points mentioned here have a far greater effect).

So yes, there are features of these languages that make it harder to generate fast machine code for them.

3

u/Klinging-on May 20 '19

Thanks, this helped my understanding greatly.

4

u/Roboguy2 May 21 '19

The cost of using higher level languages, which allow you to write code more like english, [...]

This is not what "higher level" means. "Higher level" means it allows for abstraction over certain patterns (using the word "pattern" in a somewhat general sense here).

As a simple example, C is higher level than an assembly language because you can simply call a function like this f(...) without worrying about calling conventions (adjusting the stack, setting the registers properly, etc). This makes it simpler to write function calls.

It is not really closer to English and, even if it were, that is not where its value comes from. The value of a higher-level language comes from making it easier to express certain patterns. When it is easier to express a pattern, you don't have to think about all of the internal details of it every time you encounter it (like the function call example), which frees up your mind to think about the broader aspects of the program and the problem at hand.

2

u/kireol May 21 '19

They do optimize. Java can actually be faster than C/C++ in some cases. It turns out benchmarks are hard though.

1

u/PropagandaOfTheDude May 20 '19

a compiler for a completely statically typed language would have no reason to do so

Java does array bounds checks, which introduces a delay relative to C.

17

u/frikk May 20 '19 edited May 20 '19

Sepp2k has a great answer. I'll just add something as a simple example.

In C, let's say you want to set the 5th spot in an array to a new value. You kind of just do it. The compiler takes one or two cycles to find the spot, flash the new value, and you're done. In some cases it won't even check to see if you're even allowed to do this, or if the array exists at all. If you asked to set an area that's outside of the safe memory range that your array lives in, too bad. You just flashed the value somewhere else and probably corrupted your memory.

In python, this same operation takes hundreds of cycles because a single instruction in python is actually doing tons and tons of stuff on the backend. It's going to check the type of value that you're assigning. It's going to see if the array is long enough. It may even check for other inconsistencies, like validating your value against custom rules, or running hooks on your array object or runtime class. Even if there are no hooks, it may still check for them. Further, if you're taking an action that requires adding memory to the array (like an 'append'), python will take care of that too without you even knowing or caring.

On top of all that, most of the lower level stuff is actually written in C. So then you also have to translate all of these steps from the python runtime objects into the in-memory objects that are written in C. Think of that litle array as a tiny nugget of pure memory (written in C) but wrapped in a huge runtime onion with layers and layers of abstraction, protection, translation, validation, and everything else. It's still pretty dang fast, but that's tens of extra cycles that come along with each high level step. Those python objects have to be validated and checked as well. A single array may be dozens of lines of code behind the scenes (or even hundreds of lines when you include all the boilerplate code required to translate from python world to C world -- at least for CPython).

The point is that with a language like python, you're trading speed for convenience. For many things that's an acceptable trade-off and the main reason that you would pick a language like python. If something runs in 2 seconds instead of .02 seconds, that's totally fine.

5

u/[deleted] May 20 '19

Excellent question. Here's my take on it

  • C++ and C can be architecture specific with compiler flags.

  • Java compiles to bytecode that runs on any JVM. JVM's take resources.

  • Java allocates nearly everything on the heap. That memory isn't slow, but asking for it is a syscall and has a slight hit on performance.

  • scripted languages that don't have static typing require overhead to remember what type everything is.

  • this is just conjecture, but compiler writers for c and c++ have more expectation to have high performance. Script interpreter makers dont try to make it slow, but they don't face as much criticism.

  • compiled programs start up and run immediately. Scripts and java have to fire up the interpreter/JVM which is a huge, but one time, penalty. So if you wrote grep or ls in java, it would be painfully slow because you had to pay that penalty many times. Whereas if you wrote a service in java, you'd never pay the penalty because it would always be online.

4

u/[deleted] May 20 '19 edited Jun 23 '19

[removed] — view removed comment

2

u/[deleted] May 21 '19

The problem is that python and java ARENT directly compiled to machine code, and then ran. python does the conversion on the fly, and java compiles it into an intermediate language called byte code, which is then converted on the fly.

-2

u/zanidor May 20 '19 edited May 20 '19

The language doesn't determine how long it takes a program to run, the algorithm described with the language does.

Imagine you have a GPS device that gives instructions in English, and it generally gives you the fastest route. Imagine you have another GPS device that gives instructions in Chinese, and a passenger that is translating the instructions into English for you. However, maybe your translator isn't perfect, and occasionally tells you to turn left instead of right by accident. Whenever this happens, the GPS has to reroute, and it takes you longer to get places.

In both cases you are receiving directions in English, so why does it take longer to get there with the Chinese-to-English setup? It's not the target language that's causing the slowdown, it's imperfections in the translation that makes you take a longer overall route. Similarly, translating a higher level language to a lower level one can generate something slower than the optimal low-level program since the compiler may deviate from the optimal low-level computational path.

In the case of the compiler, it's not a pure translation "error", but rather limitations on what a compiler can do while guaranteeing the output program preserves the meaning of the original. Certain high-level languages allow the compiler to generate programs closer to their low-level optimum in more cases.