4 ms·
The semantics of block-scope defer are much simpler, easier to understand, and faster. The compiler always statically knows which defers execute at any given po
by pcwalton 5y ago
The semantics of block-scope defer are much simpler, easier to understand, and faster. The compiler always statically knows which defers execute at any given point, which aids optimization. With function-scope defer, the semantics are extremely dynamic, requiring bookkeeping of a runtime stack of defer thunks, and compilers have a hard time optimizing it.
Function-scope defer is something that surprises everyone I explain it to. Programmers naturally expect defer to be block-scoped.
- kgeist 5y ago>With function-scope defer, the semantics are extremely dynamic, requiring bookkeeping of a runtime stack of defer thunks, and compilers have a hard time optimizing it. As far as I know, most functions have only one defer, and Go optimizes such cases quite trivially, by inlining calls to the deferred function at every function exit at compile time, without managing an additional stack. If there are several defers, then yes, the slow path is used.
- Thaxll 5y agoYou mixed up the two I guess?