dgryski / semgrep-go

Go rules for semgrep and go-ruleguard
MIT License
457 stars 37 forks source link

Detect slice re-creation and suggest re-use autofix instead? #62

Open dnwe opened 1 year ago

dnwe commented 1 year ago

I wonder if we can reliably suggest slice re-use rather than re-initialisation?

e.g., taking the example from the the Thanos coding-style-guide

var messages []string{}
for _, msg := range recv {
    messages = append(messages, msg)
    if len(messages) > maxMessageLen {
        marshalAndSend(messages)
        // This creates new array. Previous array
        // will be garbage collected only after
        // some time (seconds), which
        // can create enormous memory pressure.
        messages = []string{}
    }
}

=>

var messages []string{}
for _, msg := range recv {
    messages = append(messages, msg)

    if len(messages) > maxMessageLen {
        marshalAndSend(messages)
        // Instead of new array, reuse
        // the same, with the same capacity,
        // just length equals to zero.
        messages = messages[:0]
    }
}