r/AskComputerScience • • Nov 09 '25

If some programming languages are faster than others, why can't compilers translate into the faster language to make the code be as fast as if it was programed in the faster one?

My guess is that doing so would require knowing information that can't be directly inferred from the code, for example, the specific type that a variable will handle

111 Upvotes

90 comments sorted by

View all comments

Show parent comment

2

u/rxellipse Nov 10 '25

In Python, a function can take any type passed to it, and the code has to "poke" at whatever it gets at run time to see if it has the fiels and behaviors you want to use. And the types of things can get fields added to them at runtime, they aren't static.

This is true, with additional slow-downs because each object is much bigger than its actual datatype would suggest because each object also has to store its own type - an 8byte double becomes something like 32 bytes. This multiplies the amount of time it takes to copy and allocate objects, and definitely causes more cache misses. Allocating all integers on the heap (because they are all implemented as bigints instead of i32 or i64) doesn't help either.

A user-defined object with a single member field occupies 200+ bytes because it has to store a hashmap for its single member variable.

No manually controlled memory prevents a clever programmer from keeping things in cache.

But I suspect most of the slow-down comes from running the virtual machine to execute the python bytecode - the core of the runtime is a massive switch inside a while(1) loop which has to decode and execute the instructions. This additional layer of "assembly"-instructions is additional overhead, but it also prevents speculative execution from really being able to speed things up.

I think the best TLDR summary as to why python is slower than C is because:

  1. Most code that needs to run fast is probably written in C, and
  2. Therefore, new processors must be designed to run C really fast in order to be competitive in the market

Running C fast means speculative execution and minimizing cache misses, things that python (by design) is not good at.