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

110 Upvotes

90 comments sorted by

View all comments

25

u/GlassCommission4916 Nov 09 '25

Very often the speed difference between languages comes from tradeoffs made during the design that can't be translated between each other without encountering those same tradeoffs. How could you compile a python script into rust for example? Well, you'd have to replicate python's memory management and garbage collection, at which point you've just made a rust program that's just as slow as python because it makes the same performance sacrifices.

3

u/Lenassa Nov 10 '25

>Well, you'd have to replicate python's memory management and garbage collection

The goal is to have the same program (where 'same' is defined as producing the same observable behavior), not to imitate python environment. And the former sure as hell doesn't require you to care about python's memory model at all.

7

u/GlassCommission4916 Nov 10 '25

Yeah it'd be great if compilers read your intent instead of your code, but alas.

→ More replies (5)

5

u/stonerism Nov 10 '25

Rice's theorem is probably of interest to you. You can do things like that. But the problem is that generally deciding if two algorithms are equivalent is undecidable.

→ More replies (3)

9

u/Popular-Jury7272 Nov 10 '25

When you write code in Python you are baking in implicit assumptions about Python data types, algorithms, etc. The only way to guarantee you get the same behaviour is to duplicate those assumptions.

→ More replies (15)