DEV Community

Cover image for Static Lambda in C# 12 : Performance Improvement
.Net Labs
.Net Labs

Posted on

Static Lambda in C# 12 : Performance Improvement

A Static lambda, introduced in C# 12, is a lambda expression that cannot capture any variables from its enclosing scope. This means no closure class is generated, resulting in less memory allocation and potentially better performance.

Let’s work with some examples.

1. Sorting Collections:

Sorting a list of integers using a static lambda ensures no closures are created, reducing overhead during sorting

var numbers = new List<int> { 53, 31, 8, 1, 2,100,34,55,11,1 };
numbers.Sort(static (a, b) => a.CompareTo(b));
foreach (var item in numbers)
{
    Console.WriteLine(item);
}
Console.ReadKey();
Enter fullscreen mode Exit fullscreen mode

Result

Image description

2. Array Filtering
Filtering an array with a static lambda avoids capturing variables, making the filtering operation more efficient.

Console.WriteLine("--------Array Filtering-----------");
var array = new[] { 1, 2, 3, 4, 5 };
var filtered = Array.FindAll(array, static n => n > 3);
foreach (var item in filtered)
{
    Console.WriteLine(item);
}
Enter fullscreen mode Exit fullscreen mode

click here to see complete tutorial

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay