← Back to context

Comment by torginus

1 day ago

Yes it does, function-scope defer needs a dynamic data structure to keep track of pending defers, so its not zero cost.

It can be also a source of bugs where you hang onto something for longer than intended - considering there's no indication of something that might block in Go, you can acquire a mutex, defer the release, and be surprised when some function call ends up blocking, and your whole program hangs for a second.

I think it's only a real issue when you're coming from a language that has different rules. Block-scoping (and thus not being able to e.g. conditionally remove a temp file at the end of a function) would be equally surprising for someone coming from Go.

But I do definitely agree that the dynamic nature of defer and it not being block-scoped is probably not the best