Does converting from the mutable bytearray
type to the non-mutable bytes
type incur a copy? Is there any cost associated with it, or does the interpreter just treat it as an immutable byte sequence, like casting a char*
to a const char* const
in C++?
ba = bytearray()
ba.extend("some big long string".encode('utf-8'))
# Is this conversion free or expensive?
write_bytes(bytes(ba))
Does this differ between Python 3 where bytes
is its own type and Python 2.7 where bytes
is just an alias for str
?
A new copy is created, the buffer is not shared between the bytesarray
and the new bytes
object, in either Python 2 or 3.
You couldn't share it, as the bytesarray
object could still be referenced elsewhere and mutate the value.
For the details, see the bytesobject.c
source code, where the buffer protocol is used to create a straight up copy of the data (via PyBuffer_ToContiguous()
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With