diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2024-03-07-22-38-07.gh-issue-116477.AqwRAV.rst b/Misc/NEWS.d/next/Core_and_Builtins/2024-03-07-22-38-07.gh-issue-116477.AqwRAV.rst new file mode 100644 index 00000000000000..420912ace188fa --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2024-03-07-22-38-07.gh-issue-116477.AqwRAV.rst @@ -0,0 +1 @@ +Speed up the :class:`range` object constructor in the case of a single argument. diff --git a/Objects/rangeobject.c b/Objects/rangeobject.c index 2942ab624edf72..3b772f34bd3bbc 100644 --- a/Objects/rangeobject.c +++ b/Objects/rangeobject.c @@ -240,6 +240,14 @@ compute_range_length(PyObject *start, PyObject *stop, PyObject *step) assert(PyLong_Check(stop)); assert(PyLong_Check(step)); + /* fast path for one argument case of range */ + if (start == zero && step == one) { + if (_PyLong_IsPositive((const PyLongObject *)stop)) { + return Py_NewRef(stop); + } + return zero; + } + /* fast path when all arguments fit into a long integer */ long len = compute_range_length_long(start, stop, step); if (len >= 0) {