3 ms·
Tangentially related, but I like how readable the source code of CPython (the official interpreter for Python) is. It is plain C without many shenanigans. If yo
by qsantos 3y ago
Tangentially related, but I like how readable the source code of CPython (the official interpreter for Python) is. It is plain C without many shenanigans. If you wonder how Python handles big integer, hashmaps, and so on, just dive in the source code!
A few days ago, I wanted a concrete example about dynamic arrays. The examples in computer science textbook always uses a factor of 2 when expanding, since it is very convenient to demonstrate that it gives an amortized O(1) insertion time. Some people find it wasteful, and may resort to use a constant expansion (e.g. 128) instead, leading to a O(n / 128), i.e. O(n) insertion time instead.
But you can just make the expansion factor less than 2. I wanted a concrete example, so, naturally, I just went for CPython's implementation of `list`. It took me less than 2 minutes to find it: https://github.com/python/cpython/blob/main/Objects/listobject.c#L61 https://github.com/python/cpython/blob/main/Objects/listobje....
If you're curious, CPython essentially grows its dynamic array by ⅛ (12.5%) whenever it needs to.
- Yajirobe 3y agoI don't know if I can call 'new_allocated = ((size_t)newsize + (newsize >> 3) + 6) & ~(size_t)3;' very readable...
- pavlov 3y agoBy C standards that’s perfectly fine. No crazy macros, just plain old bit-twiddling. The and-not combination is a very traditional pattern for bit masking.
- deleted 3y ago[deleted]
- defrost 3y agoAs pavlov said, it's readable enough to many (those that understand bitfields). It's literally current size + (current size/8) + fiddle ( the fiddle is there to prevent a fail to increase for small input (exercise for reader?) ) followed by a mask to ensure a multiple of 8. The rational would be no floating point ops and all the weirdness that can entail plus the speed of raw shift | addition | mask. You're correct that it deserves a twice over as the fiddle raises an eyebrow that invites investigation across inputs.