Issue 27704: bytes(x) is slow when x is bytearray (original) (raw)
When bytes(x), bytes_new checks if x is integer via PyNumber_AsSize_t(x). It cause TypeError internally.
When x is not an integer, especially bytearray or memoryview, the internal exception cause significant overhead.
HEAD
$ ./python -m timeit -s 'data=bytearray(b"xyz")' 'bytes(data)' 1000000 loops, best of 3: 0.696 usec per loop $ ./python -m timeit -s 'data=bytearray(b"xyz")' 'bytes(data)' 1000000 loops, best of 3: 0.699 usec per loop $ ./python -m timeit -s 'data=bytearray(b"xyz")' 'bytes(data)' 1000000 loops, best of 3: 0.701 usec per loop
this patch
$ ./python -m timeit -s 'data=bytearray(b"xyz")' 'bytes(data)' 1000000 loops, best of 3: 0.265 usec per loop $ ./python -m timeit -s 'data=bytearray(b"xyz")' 'bytes(data)' 1000000 loops, best of 3: 0.265 usec per loop $ ./python -m timeit -s 'data=bytearray(b"xyz")' 'bytes(data)' 1000000 loops, best of 3: 0.267 usec per loop