Commit 50adfb5
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
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
831 | 831 | | |
832 | 832 | | |
833 | 833 | | |
834 | | - | |
| 834 | + | |
835 | 835 | | |
836 | 836 | | |
837 | 837 | | |
| |||
0 commit comments