However, there is an edge case in C# 7. If your local function would be implemented with a compiler-generated class (two examples I’ve
found are iterator methods and async methods), then that class will always be allocated when the outer function is invoked, whether it’s used
or not.

If the “early out” condition is taken >90% of the time, and if this function is called frequently, you may wish to avoid the
overhead of the unnecessary allocations of the compiler-generated class. Fortunately, there is a workaround: instead
of implicitly capturing the outer function’s parameter, explicitly alias it:

Now the “happy path” has zero allocations and the compiler-generated class is only instantiated if the local
function is actually called.

I wouldn’t recommend doing this by default, but if profiling indicates that extra allocations are a problem,
you may want to perform this refactoring to avoid them. I strongly recommend checking the compiled IL
to ensure that you’ve solved it. If your outer function has many parameters or locals and (due to a typo)
you inadvertently capture just one of them, then the optimization won’t kick in.

And note that in the typical “argument validation” use case for local functions, there’s no point in doing this
because the outer function should call the local function 100% of the time. (The only reason it wouldn’t
is if a boneheaded exception is thrown because the function was called incorrectly.)
This refactoring is only useful if the local function ends up being called extremely infrequently.

In that specific scenario, the MySQL client library was reading bytes from a TCP socket. Most of the time, the
bytes have already arrived and are in an OS buffer. Thus, we can immediately (and synchronously) return a
ValueTask<int> containing the number of bytes copied into the caller’s buffer. Infrequently, we have to
asynchronously wait on network I/O. Only then do we want the overhead of allocating the compiler-generated
async state machine in order to return a (wrapped) Task<int> to the caller.