Skip to content

Commit

Permalink
Merge pull request #1621 from TimFelixBeyer/patch-13
Browse files Browse the repository at this point in the history
Speed up hasElement by 2x
  • Loading branch information
mscuthbert authored Jul 1, 2023
2 parents f2146ee + 384ed9a commit 2b658aa
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 29 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
26 changes: 0 additions & 26 deletions music21/stream/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,32 +335,6 @@ def coreCopyAsDerivation(self: M21ObjType,
post.setDerivationMethod(methodName, recurse=True)
return post

def coreHasElementByMemoryLocation(self, objId: int) -> bool:
'''
NB -- a "core" stream method that is not necessary for most users. use hasElement(obj)
Return True if an element object id, provided as an argument, is contained in this Stream.
>>> s = stream.Stream()
>>> n1 = note.Note('g')
>>> n2 = note.Note('g#')
>>> s.append(n1)
>>> s.coreHasElementByMemoryLocation(id(n1))
True
>>> s.coreHasElementByMemoryLocation(id(n2))
False
'''
if objId in self._offsetDict:
return True

for e in self._elements:
if id(e) == objId: # pragma: no cover
return True
for e in self._endElements:
if id(e) == objId: # pragma: no cover
return True
return False

def coreGetElementByMemoryLocation(self, objId):
'''
NB -- a "core" stream method that is not necessary for most users.
Expand Down

0 comments on commit 2b658aa

Please sign in to comment.