Skip to content

gh-106865: Improve difflib.find_longest_match performance with cache #106877

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 23 additions & 9 deletions Lib/difflib.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,20 +371,34 @@ def find_longest_match(self, alo=0, ahi=None, blo=0, bhi=None):
# junk-free match ending with a[i-1] and b[j]
j2len = {}
nothing = []
b2jcache = {}
for i in range(alo, ahi):
# look at all instances of a[i] in b; note that because
# b2j has no junk keys, the loop is skipped if a[i] is junk
j2lenget = j2len.get
newj2len = {}
for j in b2j.get(a[i], nothing):
# a[i] matches b[j]
if j < blo:
continue
if j >= bhi:
break
k = newj2len[j] = j2lenget(j-1, 0) + 1
if k > bestsize:
besti, bestj, bestsize = i-k+1, j-k+1, k
if a[i] not in b2jcache:
cache = []
for j in b2j.get(a[i], nothing):
# a[i] matches b[j]
if j < blo:
continue
if j >= bhi:
break
cache.append(j)
k = newj2len[j] = j2lenget(j-1, 0) + 1
if k > bestsize:
besti, bestj, bestsize = i-k+1, j-k+1, k
b2jcache[a[i]] = cache
else:
for j in b2jcache[a[i]]:
# a[i] matches b[j]
if j-1 in j2len:
k = newj2len[j] = j2len[j-1] + 1
if k > bestsize:
besti, bestj, bestsize = i-k+1, j-k+1, k
else:
k = 1
j2len = newj2len

# Extend the best by non-junk elements on each end. In particular,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve performance of :func:`difflib.SequenceMatcher.find_longest_match` with a cache on hot path