Local Functions over Lambdas in WaitUntil/WaitWhile

Recently, this tweet put me on to local functions and as I dug in further, I found that in most cases, they can be used over lambdas, and if you care about readability and performance, you should use them

In my opinion, there are several benefits to using local functions over lambdas:

  • They can access local variables
  • They produce less garbage and are faster than lambdas
  • They look nicer

The performance reasons alone are enough to use them over lambdas. When a lambda is created, a delegate gets created and that causes allocations. Local functions are treated like normal functions so a delegate does not need to be created.

Also, any local vairables that you use in your local functions are usually compiled into a struct. In a lambda these are usually compiled into a class, which also avoids allocation.

We can use these local functions instead of predicates in both WaitUntil/WaitWhile

A typical Wait While function is often written like this:

yield return new WaitUntil(() => operation.IsDone);

I.e. using lambdas. You can easily replace this lambda with a local function:

bool OperationIsDone() => operation.IsDone;
var waitUntil = new WaitUntil(OperationIsDone);
yield return waitUntil;

Notice above you can use the => symbol. Whilst you may initially think this is a lambda, it is actually an expression bodied members.

So there you go, if you want a quick optimisation on your coroutines (or in fact anywhere) have a look at using local functions