r/Compilers • u/LegitimateDonut9059 • 16d ago
Why is my C++ dynamic runtime backend slower than CPython?
Hi everyone,
I'm 15 and building my own dynamically-typed programming language. The repository below is the C++ runtime/backend I wrote to handle variables, memory, and cross-type operations:
Repo: https://github.com/mxrfp/Dynamic-Type-System-in-C-
To avoid dynamic_cast and heap fragmentation, I built it around:
Double Dispatch via virtual functions to resolve operations like Int + Float or String Int.
std::pmr::unsynchronized_pool_resource inside an RAII wrapper (`Type`) to manage object lifetimes.
Since it's written in C++ with a custom memory pool, I expected it to be at least slightly faster than Python on basic benchmarks instead, it turns out to be slower than CPython.
The code is still very premature, so I'd really appreciate it if someone with more experience could take a look and help me understand where the main performance bottlenecks are.
Thanks in advance!
7
u/AdearienRDDT 16d ago
Hey, It's impressive and i commend you for going into such deep topics, and for caring about performance!
My shallow advice would be to use tools like perf and make your program run for an extended period of time, perf is a profiler and with it you will diagnose what makes your program slow, where does your program get stuck for the longest time.
Google' Benchmarking library comes to mind aswell if you wanna give it a try.
Good luck!
5
u/WittyStick 16d ago edited 16d ago
Performance issues usually come down to the machine. The primary bottleneck is still main memory access. Cache somewhat mitigates this - but only if used efficiently. Branch predictors are also essential to performance - as a correctly predicted branch has a tiny cost, but a branch misprediction can be expensive. Avoiding branch mispredictions is difficult for dynamically typed languages - but JIT-compilation can be used to reduce them.
To write high-performance dynamically typed code, you should have a good understanding of how the machine works, and how code is compiled to the ABI on your target platform.
In C++, each virtual function call must be looked up in a vtable, and an indirect branch instruction will decide where to jump. Indirect jumps rely on a branch target predictor to work well - but dynamic code doesn't really have a particular pattern which informs the predictor which virtual method will be called - so it will end up mispredicting a large number of branches.
The other issue you have is passing around pointers to
Objecteverywhere. Every dereference has a multi-cycle cost even if the value is in L1 cache - but if it isn't - and a main memory fetch is required, it costs ~100 cycles. Your CPU will be sat idle waiting for values to be read when it could be performing other instructions.Two main approaches you want to optimize a dynamically typed language:
The first thing to look at is your representation of values. Every value lives in memory - a binary operation requires 2 loads (~5 cycles each), one allocation (hundreds of cycles), one store (~5 cycles) - plus the desired operation (which is typically ~1-3 cycles), plus two indirect branches. The biggest cost is the allocation - the second biggest cost is branching - the third biggest cost is load/store.
Suppose we have an operation like:
1 + 2 * 3. We first compute2 * 3 = 6, and store this intermediate result in some allocated memory, then we load it again to add 1 to it. The intermediate result6is then just sat somewhere in memory waiting for garbage collection, even though we never needed the value6- we wanted the value7.The value
6is a value that we shouldn't need to store. It only needs to exist in a machine register temporarily, until we add1to it. We can completely avoid allocating space for this value. What we want is for integers and floats to be value types, and to only need a pointer for larger values like strings, which are reference types.The way we do this is so called "type tagging". There are lots of different techniques for it - many covered in Gudeman's 1993 paper Representing Type Information in Dynamically Typed Languages - though this is a little dated - it's still worthwhile reading to understand the techniques.
The basic idea is we want to represent a value and its type in our dynamically typed language in one or two machine registers. Where we can't fit it into the one or two registers - we hold a pointer in the machine register to a value of arbitrary size.
So for integers and floats for example - these fit into a machine register - we shouldn't need to allocate memory for them except to load and store eventual results. Strings on the other hand, require allocation because they're seldom <8-bytes (size of a register on a 64-bit machine).
A technique that works well on 64-bit SYSV platforms (Linux, Mac, BSD etc), is to use a 2-machine word struct, where one contains a type tag and the other a payload which depends on the tag.
The
sizeof(Value)is 16-bytes/128-bits. It fits nicely into two hardware registers. The SYSV ABI also supports passing this structure and returning it without having to put it on the stack.On Windows/MSVC however, the ABI only supports a single 64-bit value passed and returned in a register - so a struct like this ends up being put onto the stack, which costs us a dereference for each access. This is where some of the techniques from Gudeman's paper are relevant - where we can store both the type and the value in a single 64-bit word.
If we have 64-bit integers, 64-bit floating point, and 64-bit pointers we can't store either of these, plus a type tag in the same machine word which is only 64-bits. We have to reduce the size of our values to make space for the type tag. Consider for example, we restrict the size of our values to 48-bits, and use a 16-bit type tag - this is sufficient for pointers (48-bits is the virtual address limit on most machines). We can store a single-precision float and 32-bit integer in the payload.
Once we have a way of representing these types in this way, we can perform operations using these functions
There are other ways we can do this such as using branch tables - but for a small number of a types a switch will probably be optimized better by the compiler.
A well-known technique that allows us to use a single machine register and still use a
doubleis known as "NaN-boxing". It takes advantage of the fact that in a double-precision float, when all of the exponent bits are set to 1, the value is a NaN - the mantissa bits are irrelevant here, and there are 52 bits. 52-bits is sufficient space to store a 48-bit pointer, a 48-bit integer, and more - so we can still have a type tag and 48-bit payload in this 52-bits of space. We can do similar to the above, but we craft our type tags to only be those which are a NaN.This allows us to tag up to 14 different non-double types, with each having up to 48-bits of payload. However, we have to treat
doublespecially - since it covers all other tags which are not these 14.2
u/roeschinc 16d ago
One thing people often get tripped up on in the beginning is one language isn’t “faster” than another, so rewriting any piece of code to C++ doesn’t guarantee it will be faster.
This also extends to compilation versus interpretation. Depending on the characteristics of the language semantics you can write a slow compiler or a fast interpreter and vice versa.
It comes down to understanding what is slow about certain language semantics and what kind of optimizations can be performed to speed them up.
As others have said Python has decades of performance optimization to remove the cost of interpreting the bytecode, so your compiler must first match that performance in terms of optimization and then go further beyond that.
At a high level Python (and most interpreted languages) the main costs are lack of typing, dynamic execution semantics (function calls can be 10-100x slower easily), interpreter overhead, and then weak or inefficient programming patterns.
For example a single Python function using strings or dicts will usually beat most hand-written code because those primitives are actually incredibly well-tuned pieces of C code that execute in the runtime.
One concrete example is Python has heavily optimized the memory representation, runtime type information, and virtual dispatch for objects. Using C++ builtins to emulate the same behavior is likely to be worse for a number of reasons.
If you want a deeper understanding you can likely find a few books / chat with an LLM to explain how they implement these efficiently.
2
u/realrealvantheman 16d ago edited 16d ago
Because CPython has had decades of optimization work done by the best in the field. That simple. If there is a trick that exists, it is probably implimented in CPython, Lua, Linux, or another giant. I mostly work in C and assembler and would probably not be able to make much sense of the codebase of yours if I read it, so I cant help on that. (I cant read c++ very well lol)
1
u/AustinVelonaut 16d ago
The Double dispatch mechanism is a clean way to dispatch to an ultimate binary operation (it was used heavily in Smalltalk implementations, too), and it handles all combinations of operand types, but it does require three indirect jumps for each operation. Since it is much more common to encounter a binary operation on two of the same type, most systems check for the common same-type case first, e.g. try a quick check of Int/Int, then call int.op directly, otherwise fall back to double-dispatch.
1
u/Dan13l_N 15d ago
TBH this is very weird. Python is really slow. My toy (statically typed) language is often 10 x faster than Python.
Are you sure you are building your benchmarks with maximum optimization level?
Also, what benchmarks are you using? In my experience, only looping a million times -- or some big number like that -- over a section of code will give you some real numbers.
0
u/[deleted] 16d ago edited 16d ago
There are reasons why CPython uses C rather than C++. With C it has much more control.
But, you don't yet have an actual interpreter loop, just type dispatch?
So, what is the actual task being compared, and how slower is your backend than CPython? How is it being measured?
CPython is generally considered slow, and difficult to speed up because of how dynamic Python is and being able to overload operators and so on. But I don't know how much of that applies to your tests.
My own type dispatch is brisker than CPython and is simple (but I don't have arbitrary overloads).
So if I'm doing ADD between A and B for example, then I first do a quick check to see if they both are ints or both floats, otherwise the next check is whether they the same type, then only single dispatch is needed.