style: defer unlock when possible/not trivial

Defer unlocking just after taking a lock when possible (when unlock is
done at the very end) and when not trivial (the function body is more
than a couple of lines). This simplifies a bit some functions (no need
to unlock before each return) and for the other, it may avoid a bug in
the future in case a return is inserted into the body of a function.

Use of defer has been optimized a lot in Go and it is believed that
simpler defers have zero overhead since Go 1.14:
https://golang.org/doc/go1.14#runtime

> This release improves the performance of most uses of defer to incur
> almost zero overhead compared to calling the deferred function
> directly. As a result, defer can now be used in performance-critical
> code without overhead concerns.
This commit is contained in:
Vincent Bernat
2021-09-23 09:57:14 +02:00
parent defd786b2a
commit 95945d3042
4 changed files with 6 additions and 13 deletions

View File

@@ -53,12 +53,12 @@ func FindFormat(ctx context.Context, name string) (*Format, error) {
func GetFormats() []string {
lock.RLock()
defer lock.RUnlock()
t := make([]string, len(formatDrivers))
var i int
for k, _ := range formatDrivers {
t[i] = k
i++
}
lock.RUnlock()
return t
}