3 ms·
This behaviour (id not changing after concatenation) is consistent with the original str object being deallocated and a new one allocated in its place with an i
by pwdisswordfish6 6y ago
This behaviour (id not changing after concatenation) is consistent with the original str object being deallocated and a new one allocated in its place with an identical id. It’s not what actually happens behind the scenes (in CPython), but it’s still an implementation detail that this demonstration does not even unambiguously expose.
- nine_k 6y agoCPython could do both; allocations are usually not byte-perfect, and the small remaining room at the end of string can be used as an optimization, or a new buffer can be allocated if there's no more room. Also, cutting long strings with .strip() can use the same optimization. Allocation isn't fast. IDK if it's used, but it's entirely plausible to implement.
- masklinn 6y ago> CPython could do both; allocations are usually not byte-perfect Though it's probably not the case for strings, it should be noted that for most objects allocations are byte-perfect, because the average Python object is a bunch of pointers and and a refcount: two gc pointers, a refcount, a weakref pointer, a class pointer and a dict pointer, for a total of 48 bytes (as of 3.9, ignoring all the pointees). That's not the case for `__slots__` though: they drop the instance dict and the weakref pointer, but then each field will add a pointer to the total (then again that's space which won't be allocated as part of the instance dict).
- duckerude 6y agoCouldn't the old object only ever get deallocated after the new one is allocated?
- mark-r 6y agoI was about to say that. The old buffer has to be copied to the new buffer, so a naive implementation couldn't possibly allocate them both at the same address.