8000 bpo-46841: Avoid unnecessary allocations in code object comparisons (… · python/cpython@bd2e47c · GitHub
[go: up one dir, main page]

Skip to content

Commit bd2e47c

Browse files
authored
bpo-46841: Avoid unnecessary allocations in code object comparisons (GH-32222)
1 parent a0ea7a1 commit bd2e47c

File tree

2 files changed

+14
-13
lines changed

2 files changed

+14
-13
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Avoid unnecessary allocations when comparing code objects.

Objects/codeobject.c

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1398,21 +1398,21 @@ code_richcompare(PyObject *self, PyObject *other, int op)
13981398
if (!eq) goto unequal;
13991399
eq = co->co_firstlineno == cp->co_firstlineno;
14001400
if (!eq) goto unequal;
1401-
PyObject *co_code = _PyCode_GetCode(co);
1402-
if (co_code == NULL) {
1403-
return NULL;
1404-
}
1405-
PyObject *cp_code = _PyCode_GetCode(cp);
1406-
if (cp_code == NULL) {
1407-
Py_DECREF(co_code);
1408-
return NULL;
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 (int i = 0; i < Py_SIZE(co); i++) {
1406+
_Py_CODEUNIT co_instr = _PyCode_CODE(co)[i];
1407+
_Py_CODEUNIT cp_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+
}
14161416

14171417
/* compare constants */
14181418
consts1 = _PyCode_ConstantKey(co->co_consts);

0 commit comments

Comments
 (0)
0