Skip to content

Commit

Permalink
pythongh-93382: Cache result of PyCode_GetCode in codeobject (pytho…
Browse files Browse the repository at this point in the history
…nGH-93383)

Co-authored-by: Kumar Aditya <[email protected]>
Co-authored-by: Dennis Sweeney <[email protected]>
  • Loading branch information
3 people committed Jun 4, 2022
1 parent 1497d7f commit 13642ce
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 42 deletions.
1 change: 1 addition & 0 deletions Include/cpython/code.h
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ typedef uint16_t _Py_CODEUNIT;
PyObject *co_qualname; /* unicode (qualname, for reference) */ \
PyObject *co_linetable; /* bytes object that holds location info */ \
PyObject *co_weakreflist; /* to support weakrefs to code objects */ \
void *_co_code; /* cached co_code object/attribute */ \
/* Scratch space for extra data relating to the code object. \
Type is a void* to keep the format private in codeobject.c to force \
people to go through the proper APIs. */ \
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Speed up the :c:func:`PyCode_GetCode` function which also improves accessing the :attr:`~types.CodeType.co_code` attribute in Python.
7 changes: 7 additions & 0 deletions Objects/codeobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ init_code(PyCodeObject *co, struct _PyCodeConstructor *con)
/* not set */
co->co_weakreflist = NULL;
co->co_extra = NULL;
co->_co_code = NULL;

co->co_warmup = QUICKENING_INITIAL_WARMUP_VALUE;
memcpy(_PyCode_CODE(co), PyBytes_AS_STRING(con->code),
Expand Down Expand Up @@ -1367,12 +1368,17 @@ deopt_code(_Py_CODEUNIT *instructions, Py_ssize_t len)
PyObject *
_PyCode_GetCode(PyCodeObject *co)
{
if (co->_co_code != NULL) {
return Py_NewRef(co->_co_code);
}
PyObject *code = PyBytes_FromStringAndSize((const char *)_PyCode_CODE(co),
_PyCode_NBYTES(co));
if (code == NULL) {
return NULL;
}
deopt_code((_Py_CODEUNIT *)PyBytes_AS_STRING(code), Py_SIZE(co));
assert(co->_co_code == NULL);
co->_co_code = (void *)Py_NewRef(code);
return code;
}

Expand Down Expand Up @@ -1531,6 +1537,7 @@ code_dealloc(PyCodeObject *co)
Py_XDECREF(co->co_qualname);
Py_XDECREF(co->co_linetable);
Py_XDECREF(co->co_exceptiontable);
Py_XDECREF(co->_co_code);
if (co->co_weakreflist != NULL) {
PyObject_ClearWeakRefs((PyObject*)co);
}
Expand Down
42 changes: 0 additions & 42 deletions Programs/test_frozenmain.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 13642ce

Please sign in to comment.