3 ms·
To avoid the function overhead, you can also defer the Close() and explicitly call Close() at the end: defer rows.Close() /* do things */ err = row
by SPBS 4y ago
To avoid the function overhead, you can also defer the Close() and explicitly call Close() at the end:
defer rows.Close()
/* do things */
err = rows.Close()
if err != nil {
}
1. If the explicit Close() is called first, the error from the deferred Close() is ignored.
2. If the explicit Close() is never called because of a panic, the deferred Close() will kick in and cleanup the resources.
- arp242 4y agoIs that actually faster? You're saving the (small) overhead of an extra function, but you're adding a new function call. Certainly in the context of an SQL query (which will take milliseconds at the least) I wouldn't expect a few nanoseconds to matter.
- SPBS 4y agoThat's true. However I also like to not mess around with any deferred functions that have to capture an error variable by name (named returns) or by pointer so that it can modify the error on the way out. Calling rows.Close() after you're done with rows is a simple 4-line addition that doesn't require rewriting the already existing defer rows.Close(), which lowers the cognitive load in my opinion. Like you said, the performance gains (if any) are probably not going to matter when a database call is involved.