来源:https://stackoverflow.com/questions/41915305/is-there-any-benefit-to-using-py-decref-instead-of-py-xdecref-for-python-c-exten
If you know that the object cannot be NULL, the benefits of Py_DECREF
over Py_XDECREF
are that:
- it is faster, since it avoids an unnecessary test and jump;
- it signals to the (human) reader that the pointer is expected to be non-NULL at the point of deallocation;
- it provides what is effectively a zero-cost assertion that the pointer is non-NULL - the program is likely to immediately crash if the invariant is broken.¹
These points can be important when dealing with low-level code, which is why Python core and most extensions are careful to only use Py_XDECREF
(or Py_CLEAR
in tp_clear
) when the pointer can actually be NULL.
Technically it's undefined behavior, which means that a crash is not guaranteed the way it would be with an actual assertion. In practice, however, the compiler has little choice but to generate code that dereferences the pointer, which will lead to a memory fault if it is NULL.