Runtime overhead of using defer in go

Aniruddha
Aniruddha
Mar 7, 2018 · 2 min read

Golang has a pretty nifty keyword named defer. As explained here, a defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.

Using defer, however, is not free. Using go’s benchmarking support, we can try to quantify this overheard.

The following two functions do the same work, but one calls a function in a defer statement while the other doesn’t

Let’s benchmark these —

Running this with go -bench on an 8 core google cloud VM gives us

As expected, both these functions don’t allocate any memory. But doDefer is roughly 16 times more expensive than doNoDefer. To understand why defer is this expensive, let’s look at the disassembled code.

The disassembly for the actual functions called inside doDefer and doNoDefer is the same

The doNoDefer sets up the necessary registers and then calls main.doNoDefer.func1

The doDefer function also sets up registers, but there are additional function calls — the first one to runtime.deferproc which sets up the deferred function to be called. The second one is to runtime.deferreturn — which in turn calls itself for every defer statement encountered in the function.

deferproc and deferreturn are both non-trivial functions and they do a bunch of accounting and setup at entry and exit. In short, don’t use defer in hot code paths. The overhead is non-trivial and not obvious.

i0exception

Wut?

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store