Skip to content

Commit 50adfb5

Browse files
committed
byte_from_int(): minor performance optimization
This seems to be consistently faster than the previous approach `bytes((i,))`. ```console $ python3 --version Python 3.14.2 $ python3 -m timeit -s 'import struct; packer_u1 = struct.Struct("B")' 'packer_u1.pack(91)' 5000000 loops, best of 5: 43.6 nsec per loop $ python3 -m timeit 'bytes((91,))' 2000000 loops, best of 5: 107 nsec per loop $ python3 -m timeit '(91).to_bytes(1, "big")' 5000000 loops, best of 5: 57.7 nsec per loop $ python3 -m timeit '(91).to_bytes()' 5000000 loops, best of 5: 46.4 nsec per loop ``` You can see that `int.to_bytes()` is similarly fast as the first `struct` approach, but it still seems to be a bit slower and is only available since Python 3.11, see https://docs.python.org/3/library/stdtypes.html#int.to_bytes: > Changed in version 3.11: Added default argument values for `length` > and `byteorder`. Python 3.10 forces you to provide these arguments explicitly (which, as we've seen, slows down the entire call): ```console $ python3 --version Python 3.10.12 $ python3 -c 'print((91).to_bytes())' Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: to_bytes() missing required argument 'length' (pos 1) $ python3 -c 'print((91).to_bytes(1))' Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: to_bytes() missing required argument 'byteorder' (pos 2) $ python3 -c 'print((91).to_bytes(1, "big"))' b'[' ```
1 parent 115c3bd commit 50adfb5

1 file changed

Lines changed: 1 addition & 1 deletion

File tree

kaitaistruct.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -831,7 +831,7 @@ def int_from_byte(v):
831831

832832
@staticmethod
833833
def byte_from_int(i):
834-
return bytes((i,))
834+
return KaitaiStream.packer_u1.pack(i)
835835

836836
@staticmethod
837837
def byte_array_index(data, i):

0 commit comments

Comments
 (0)