Permalink
Browse files

Very mild optimization, O(1) for O(n)

I don't know how often this function is called, but this O(1) lookup is faster
even in the best case of the set of ifs it replaces.  In the worst case (rop ==
'ge') it's more than 3 times as fast.
  • Loading branch information...
1 parent e64419a commit 84ed8d601edd91dc0e7ed0bf7c2991fba9719446 @hunteke hunteke committed Jan 16, 2012
Showing with 27 additions and 7 deletions.
  1. +27 −7 sympy/core/relational.py
View
@@ -127,15 +127,15 @@ class Relational(Expr, EvalfMixin):
is_Relational = True
+ # ValidRelationOperator - Defined below, because the necessary classes
+ # have not yet been defined
+
@staticmethod
def get_relational_class(rop):
- if rop is None or rop in ('==','eq'): return Equality
- if rop in ('!=','<>','ne'): return Unequality
- if rop in ('<','lt'): return StrictLessThan
- if rop in ('<=','le'): return LessThan
- if rop in ('>','gt'): return StrictGreaterThan
- if rop in ('>=','ge'): return GreaterThan
- raise ValueError("Invalid relational operator symbol: %r" % (rop))
+ try:
+ return Relational.ValidRelationOperator[ rop ]
+ except KeyError:
+ raise ValueError("Invalid relational operator symbol: %r" % (rop))
def __new__(cls, lhs, rhs, rop=None, **assumptions):
lhs = _sympify(lhs)
@@ -349,3 +349,23 @@ def __eq__ ( self, other ):
st = self._hashable_content()
return st == ot
+
+# A class (not object) specific data item used for a minor speedup. It is
+# defined here, rather than directly in the class, because the classes that it
+# references have not been defined until now (e.g. StrictLessThan).
+Relational.ValidRelationOperator = {
+ None : Equality,
+ '==' : Equality,
+ 'eq' : Equality,
+ '!=' : Unequality,
+ '<>' : Unequality,
+ 'ne' : Unequality,
+ '>=' : GreaterThan,
+ 'ge' : GreaterThan,
+ '<=' : LessThan,
+ 'le' : LessThan,
+ '>' : StrictGreaterThan,
+ 'gt' : StrictGreaterThan,
+ '<' : StrictLessThan,
+ 'lt' : StrictLessThan,
+}

0 comments on commit 84ed8d6

Please sign in to comment.