The other day in one of my utilities, ReSharper hinted me about the piece of code below stating that lambda defining the delegate ThreadStart
can be turned into a local function:
public void Start(ThreadPriority threadPriority = ThreadPriority.Lowest)
{
if (!Enabled)
{
_threadCancellationRequested = false;
ThreadStart threadStart = () => NotificationTimer (ref _interval, ref _ignoreDurationThreshold, ref _threadCancellationRequested);
Thread = new Thread(threadStart) {Priority = ThreadPriority.Lowest};
Thread.Start();
}
}
And hence transformed into:
public void Start(ThreadPriority threadPriority = ThreadPriority.Lowest)
{
if (!Enabled)
{
_threadCancellationRequested = false;
void ThreadStart() => NotificationTimer(ref _interval, ref _ignoreDurationThreshold, ref _threadCancellationRequested);
Thread = new Thread(ThreadStart) {Priority = ThreadPriority.Lowest};
Thread.Start();
}
}
What are the benefits of the latter over the former, is it only about performance?
I've already checked the resources below but in my example the benefits are not that obvious:
C is one of the most powerful "modern" programming language, in that it allows direct access to memory and many "low level" computer operations. C source code is compiled into stand-a-lone executable programs.
Being a middle-level language, C reduces the gap between the low-level and high-level languages. It can be used for writing operating systems as well as doing application level programming. Helps to understand the fundamentals of Computer Theories.
The 1st website you linked mentions some benefits of local functions:
- A lambda causes allocation.
- There's no elegant way of writing a recursive lambda.
- They can't use yield return
and probably some other things.
One useful use-case is iterators:
Wrong way:
public static IEnumerable<T> SomeExtensionMethod<T>(this IEnumerable<T> source) {
//Since this method uses deferred execution,
//this exception will not be thrown until enumeration starts.
if (source == null)
throw new ArgumentNullException();
yield return something;
}
Right way:
public static IEnumerable<T> SomeExtensionMethod<T>(this IEnumerable<T> source) {
if (source == null)
throw new ArgumentNullException();
return Iterator();
IEnumerable<T> Iterator() {
yield return something;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With