Skip to content
Open
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
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,10 @@
splicing the unchanged blocks into each parent's child list in a single pass rather
than removing and re-inserting each one, which rescanned and shifted the whole child
list on every conversion (#5213)
- Improve performance of `--preview` string merging on lines such as
`"%s ..." % (a, b, c, ...)` by copying the leaves that surround the merged string in
one `append_leaves` call instead of one call per leaf, which rescanned the shared
parent's child list from the start every time (#5220)

### Output

Expand Down
15 changes: 14 additions & 1 deletion src/black/trans.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,18 @@ def _merge_string_group(
new_line = line.clone()
previous_merged_string_idx = -1
previous_merged_num_of_strings = -1
# Leaves outside any merged string group are copied in runs rather than
# one at a time. append_leaves resumes the search for each leaf's
# position from where the previous sibling of the same parent was found,
# so copying a run of leaves that share a parent (the operand tuple of
# "%s ..." % (a, b, c, ...)) stays linear; a fresh call per leaf restarts
# that search from the front every time and is quadratic in the operands.
pending: list[Leaf] = []
for i, leaf in enumerate(LL):
if i in merged_string_idx_dict:
if pending:
append_leaves(new_line, line, pending)
pending = []
previous_merged_string_idx = i
previous_merged_num_of_strings, string_leaf = merged_string_idx_dict[i]
new_line.append(string_leaf)
Expand All @@ -594,7 +604,10 @@ def _merge_string_group(
new_line.append(comment_leaf, preformatted=True)
continue

append_leaves(new_line, line, [leaf])
pending.append(leaf)

if pending:
append_leaves(new_line, line, pending)

return Ok(new_line)

Expand Down
Loading