From 4945b032f15af1e98324db62c8e4938812910203 Mon Sep 17 00:00:00 2001 From: Brandt Bucher Date: Thu, 31 Mar 2022 14:48:57 -0700 Subject: [PATCH 1/2] Compare instructions one-by-one --- Objects/codeobject.c | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Objects/codeobject.c b/Objects/codeobject.c index 224493edb19ea3..987cdef3c90d4f 100644 --- a/Objects/codeobject.c +++ b/Objects/codeobject.c @@ -1398,21 +1398,21 @@ code_richcompare(PyObject *self, PyObject *other, int op) if (!eq) goto unequal; eq = co->co_firstlineno == cp->co_firstlineno; if (!eq) goto unequal; - PyObject *co_code = _PyCode_GetCode(co); - if (co_code == NULL) { - return NULL; - } - PyObject *cp_code = _PyCode_GetCode(cp); - if (cp_code == NULL) { - Py_DECREF(co_code); - return NULL; - } - eq = PyObject_RichCompareBool(co_code, cp_code, Py_EQ); - Py_DECREF(co_code); - Py_DECREF(cp_code); - if (eq <= 0) { + eq = Py_SIZE(co) == Py_SIZE(cp); + if (!eq) { goto unequal; } + for (int i = 0; i < Py_SIZE(co); i++) { + _Py_CODEUNIT co_instr = _PyCode_CODE(co)[i]; + _Py_CODEUNIT cp_instr = _PyCode_CODE(cp)[i]; + _Py_SET_OPCODE(co_instr, _PyOpcode_Deopt[_Py_OPCODE(co_instr)]); + _Py_SET_OPCODE(cp_instr, _PyOpcode_Deopt[_Py_OPCODE(cp_instr)]); + eq = co_instr == cp_instr; + if (!eq) { + goto unequal; + } + i += _PyOpcode_Caches[_Py_OPCODE(co_instr)]; + } /* compare constants */ consts1 = _PyCode_ConstantKey(co->co_consts); From bed7aa0b800eaef5fac1f5946943e8ebdf4ac69a Mon Sep 17 00:00:00 2001 From: Brandt Bucher Date: Thu, 31 Mar 2022 15:57:51 -0700 Subject: [PATCH 2/2] blurb add --- .../Core and Builtins/2022-03-31-15-57-42.bpo-46841.U-25Z6.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2022-03-31-15-57-42.bpo-46841.U-25Z6.rst diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-03-31-15-57-42.bpo-46841.U-25Z6.rst b/Misc/NEWS.d/next/Core and Builtins/2022-03-31-15-57-42.bpo-46841.U-25Z6.rst new file mode 100644 index 00000000000000..42711cd40f3962 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2022-03-31-15-57-42.bpo-46841.U-25Z6.rst @@ -0,0 +1 @@ +Avoid unnecessary allocations when comparing code objects.