Skip to content
Open
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
19 changes: 13 additions & 6 deletions build/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -1032,12 +1032,19 @@ func (p *printer) useCompactMode(start *Position, list *[]Expr, end *End, mode s
// If multiLine is true, seq avoids the compact form even
// for 0- and 1-element sequences.
func (p *printer) seq(brack string, start *Position, list *[]Expr, end *End, mode seqMode, forceCompact, forceMultiLine bool) {
args := &[]Expr{}
for _, x := range *list {
// nil arguments may be added by some linter checks, filter them out because
// they may cause NPE.
if x != nil {
*args = append(*args, x)
// Filter out nil arguments (rare; added by some linter checks) that may cause a NPE, copying only if needed.
args := list
for i, x := range *list {
if x == nil {
filtered := make([]Expr, i, len(*list))
copy(filtered, (*list)[:i])
for _, y := range (*list)[i+1:] {
if y != nil {
filtered = append(filtered, y)
}
}
args = &filtered
break
}
}
Comment on lines +1036 to 1049

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When a nil element is found, we can optimize the filtering process by avoiding a full second pass over the entire slice. Instead, we can create the filtered slice with a length equal to the index i of the first nil element, use the highly optimized built-in copy function to copy the non-nil prefix, and then only loop over the remaining elements starting from i+1. Ensure that this optimization is consistent with the previous behavior and does not introduce any unintended side effects.

Suggested change
args := list
for _, x := range *list {
// nil arguments may be added by some linter checks, filter them out because
// they may cause NPE.
if x != nil {
*args = append(*args, x)
if x == nil {
filtered := make([]Expr, 0, len(*list))
for _, y := range *list {
if y != nil {
filtered = append(filtered, y)
}
}
args = &filtered
break
}
}
args := list
for i, x := range *list {
if x == nil {
filtered := make([]Expr, i, len(*list))
copy(filtered, (*list)[:i])
for _, y := range (*list)[i+1:] {
if y != nil {
filtered = append(filtered, y)
}
}
args = &filtered
break
}
}
References
  1. When modifying code, ensure that changes are consistent with previous behavior, especially if the previous behavior was intentional.


Expand Down