[Cython] Inefficient code for "is None" in boolean expressions that mix Python and C

Stefan Behnel stefan_ml at behnel.de
Fri Feb 1 16:50:28 CET 2008


Hi,

I noticed that "is None" in a boolean expression gets unnecessarily evaluated
in Python space. This code:

----------------------
        if stop is None and (start is None or start == 0):
----------------------

gets compiled into this totally redundant code (plus error handling):

----------------------
__pyx_1 = (__pyx_v_stop == Py_None);
__pyx_2 = __Pyx_PyBool_FromLong(__pyx_1);
__pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2);
if (__pyx_1) {
  Py_DECREF(__pyx_2); __pyx_2 = 0;
  __pyx_1 = (__pyx_v_start == Py_None);
  __pyx_2 = __Pyx_PyBool_FromLong(__pyx_1);
  __pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2);
  if (!__pyx_1) {
    Py_DECREF(__pyx_2); __pyx_2 = 0;
    __pyx_2 = PyObject_RichCompare(__pyx_v_start, __pyx_num_0, Py_EQ);
  }
}
__pyx_1 = __Pyx_PyObject_IsTrue(__pyx_2);
Py_DECREF(__pyx_2); __pyx_2 = 0;
if (__pyx_1) {
----------------------

The only thing that needs Python evaluation here is "start == 0", the rest
could run entirely in C. I don't know if it's a more general problem, though,
since all C tests should be evaluated in plain C code.

Stefan



More information about the Cython-dev mailing list