[Python-Dev] Comparison speed

Tim Peters tim.one@home.com
Tue, 15 May 2001 19:49:03 -0400


Making the 5am email concrete, this is what I meant:

Index: object.c
===================================================================
RCS file: /cvsroot/python/python/dist/src/Objects/object.c,v
retrieving revision 2.131
diff -c -r2.131 object.c
*** object.c	2001/05/11 03:36:45	2.131
--- object.c	2001/05/15 23:39:24
***************
*** 835,841 ****
  		}
  	}
  	else {
! 		res = do_richcmp(v, w, op);
  	}
  	compare_nesting--;
  	return res;
--- 835,863 ----
  		}
  	}
  	else {
! 		cmpfunc f;
! 		if (v->ob_type == w->ob_type
! 		    && RICHCOMPARE(v->ob_type) == NULL
! 		    && (f = v->ob_type->tp_compare) != NULL)
! 		{
! 			int c = (*f)(v, w);
! 			if (c < 0 && PyErr_Occurred())
! 				res = NULL;
! 			else {
! 				switch (op) {
! 					case Py_LT: c = c <  0; break;
! 					case Py_LE: c = c <= 0; break;
! 					case Py_EQ: c = c == 0; break;
! 					case Py_NE: c = c != 0; break;
! 					case Py_GT: c = c >  0; break;
! 					case Py_GE: c = c >= 0; break;
! 				}
! 				res = c ? Py_True : Py_False;
! 				Py_INCREF(res);
! 			}
! 		}
! 		else
! 			res = do_richcmp(v, w, op);
  	}
  	compare_nesting--;
  	return res;

That's a local change to PyObject_RichCompare, taking a fast path for most
scalar types (which don't have richcmps but do have tp_compare today).  On my
Win98 box reproducible timings are impossible, but it obviously chops out
layers and layers of function calls and redundant tests when it triggers.
That appears to be more often than not across all apps I've tried, from 60%
of PyObject_RichCompare calls to nearly 100%.