Skip to content

Commit e6ef5e1

Browse files
committed
Check bytes exact first to speed up that case
from_bytes_flags: Mean +- std dev: [main] 28.3 ns +- 1.3 ns -> [exactbytes] 27.3 ns +- 0.3 ns: 1.04x faster bench_convert[bytearray]: Mean +- std dev: [main] 65.8 ns +- 3.3 ns -> [exactbytes] 53.1 ns +- 5.1 ns: 1.24x faster bench_convert_big[bytes]: Mean +- std dev: [main] 51.8 ns +- 0.6 ns -> [exactbytes] 50.3 ns +- 0.5 ns: 1.03x faster bench_convert_big[bytearray]: Mean +- std dev: [main] 65.8 ns +- 3.0 ns -> [exactbytes] 53.5 ns +- 5.3 ns: 1.23x faster Benchmark hidden because not significant (1): bench_convert[bytes]
1 parent b078ea1 commit e6ef5e1

2 files changed

Lines changed: 6 additions & 2 deletions

File tree

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
Speed up :meth:`int.from_bytes` when passed object supports :ref:`buffer
2-
protocol <bufferobjects>`, like :class:`bytearray`.
2+
protocol <bufferobjects>`, like :class:`bytearray` by ~1.2x.

Objects/longobject.c

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6454,7 +6454,11 @@ int_from_bytes_impl(PyTypeObject *type, PyObject *bytes_obj,
64546454
}
64556455

64566456
/* Use buffer protocol to avoid copies. */
6457-
if (PyObject_CheckBuffer(bytes_obj)) {
6457+
if (PyBytes_CheckExact(bytes_obj)) {
6458+
long_obj = _PyLong_FromByteArray(
6459+
(unsigned char *)PyBytes_AS_STRING(bytes_obj), Py_SIZE(bytes_obj),
6460+
little_endian, is_signed);
6461+
} else if (PyObject_CheckBuffer(bytes_obj)) {
64586462
if (PyObject_GetBuffer(bytes_obj, &view, PyBUF_SIMPLE) != 0) {
64596463
return NULL;
64606464
}

0 commit comments

Comments
 (0)