bpo-46841: Avoid unnecessary allocations in code object comparisons (… · python/cpython@bd2e47c

GitHub

File tree

Misc/NEWS.d/next/Core and Builtins

Objects

Original file line numberDiff line numberDiff line change@@ -0,0 +1 @@

1+Avoid unnecessary allocations when comparing code objects.

Original file line numberDiff line numberDiff line change@@ -1398,21 +1398,21 @@ code_richcompare(PyObject *self, PyObject *other, int op)

13981398if (!eq) goto unequal;

13991399eq=co->co_firstlineno==cp->co_firstlineno;

14001400if (!eq) goto unequal;

1401-PyObject*co_code=_PyCode_GetCode(co);

1402-if (co_code==NULL) {

1403-returnNULL;

1404- }

1405-PyObject*cp_code=_PyCode_GetCode(cp);

1406-if (cp_code==NULL) {

1407-Py_DECREF(co_code);

1408-returnNULL;

1409- }

1410-eq=PyObject_RichCompareBool(co_code, cp_code, Py_EQ);

1411-Py_DECREF(co_code);

1412-Py_DECREF(cp_code);

1413-if (eq <= 0) {

1401+eq=Py_SIZE(co) ==Py_SIZE(cp);

1402+if (!eq) {

14141403 goto unequal;

14151404 }

1405+for (inti=0; i<Py_SIZE(co); i++) {

1406+_Py_CODEUNITco_instr=_PyCode_CODE(co)[i];

1407+_Py_CODEUNITcp_instr=_PyCode_CODE(cp)[i];

1408+_Py_SET_OPCODE(co_instr, _PyOpcode_Deopt[_Py_OPCODE(co_instr)]);

1409+_Py_SET_OPCODE(cp_instr, _PyOpcode_Deopt[_Py_OPCODE(cp_instr)]);

1410+eq=co_instr==cp_instr;

1411+if (!eq) {

1412+ goto unequal;

1413+ }

1414+i+=_PyOpcode_Caches[_Py_OPCODE(co_instr)];

1415+ }

1416141614171417/* compare constants */

14181418consts1=_PyCode_ConstantKey(co->co_consts);