improvement(utils): Use deque instead of list for BFS#147
Open
barucden wants to merge 1 commit into
Open
Conversation
`list.pop(0)` has linear complexity (in the number of list members), so the previous BFS implementation had a quadratic complexity.
I used this program to measure the difference:
```python
import time
from lxml import etree
from xmldiff import main as xmldiff
def make_xml(breadth, depth, tweak_last=False):
"""Generate an XML string with `breadth` children per node, `depth` levels."""
lines = ['<root>']
def build(level, path):
if level >= depth:
return
for i in range(breadth):
tag = f"n{i}"
attr = f' v="{path}_{i}"'
# Tweak the very last leaf to force a diff
if tweak_last and level == depth - 1 and i == breadth - 1:
attr += ' changed="true"'
lines.append(f'<{tag}{attr}>')
build(level + 1, f"{path}_{i}")
lines.append(f'</{tag}>')
build(0, "r")
lines.append('</root>')
return etree.fromstring('\n'.join(lines))
def main():
breadth = 5
depth = 5
left = make_xml(breadth, depth)
right = make_xml(breadth, depth, tweak_last=True)
start = time.perf_counter()
xmldiff.diff_trees(left, right)
elapsed = time.perf_counter() - start
# Count nodes for reference
total = sum(breadth ** i for i in range(depth + 1))
print(f"nodes={total} time={elapsed:.4f}s")
if __name__ == "__main__":
main()
```
The current version was approximately 300ms faster than master.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
list.pop(0)has linear complexity (in the number of list members), so the previous BFS implementation had a quadratic complexity.I used this program to measure the difference:
The current version was approximately 300ms faster than master.