Skip to content

Commit

Permalink
Speed up hasElement by 2x
Browse files Browse the repository at this point in the history
use python `is` identity check instead of comparing the result of `id` between elements.
  • Loading branch information
TimFelixBeyer authored Jun 26, 2023
1 parent 9fe595f commit 384ed9a
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions music21/stream/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1434,7 +1434,7 @@ def mergeAttributes(self, other: base.Music21Object):
if hasattr(other, attr):
setattr(self, attr, getattr(other, attr))

def hasElement(self, obj):
def hasElement(self, obj: base.Music21Object) -> bool:
'''
Return True if an element, provided as an argument, is contained in
this Stream.
Expand All @@ -1449,8 +1449,16 @@ def hasElement(self, obj):
>>> s.hasElement(n1)
True
'''
objId = id(obj)
return self.coreHasElementByMemoryLocation(objId)
if id(obj) in self._offsetDict:
return True

for e in self._elements:
if e is obj: # pragma: no cover
return True
for e in self._endElements:
if e is obj: # pragma: no cover
return True
return False

def hasElementOfClass(self, className, forceFlat=False):
'''
Expand Down

0 comments on commit 384ed9a

Please sign in to comment.