Resharper can be used to ‘inspect’  your current codebase –  based on which, it makes ‘recommendations’ about your code. One of the things that Resharper discovers is  ‘Language usage opportunities’ –  wherein newer c# statements can be used in place of older ones.

One such interesting ‘usage opportunity’ is replacing the older foreach loops. These can be rewritten using LINQ as shown in the example below.

The example uses a foreach iteration over a  Routes collection (An MVC home controller may contain a foreach loop as shown below):

   1: List<string> apis = new List<string>();

   2:               foreach (System.Web.Routing.Route route in routeCollection)

   3:               {

   4:                   apis.Add(route.Url);

   5:               }

can be replaced with

   1: System.Web.Routing.RouteCollection routeCollection = System.Web.Routing.RouteTable.Routes;

   2: List<string> apis = (from Route route in routeCollection select route.Url).ToList();

What struck me was that this was more than just a ‘language usage’ improvement. This would offer a significant performance improvement as well.

Will LINQ be faster?

In general Yes – but not always. For smaller sized collections, a foreach loop may outperform a linq expression. A bit surprising, but true. However, as collection sizes grow, LINQ clearly outperforms foreach loops.

If LINQ is not clearly faster, when should I use it?

For data that is clearly destined to grow (collection of new customers or new accounts etc.), LINQ is a better choice. For relatively  unchanging collections (example – the route collection listed above – will only grow by a few new routes – and is typically going to be under 3000 routes), the foreach may still have it’s place. This post provides a sample solution to run your own comparison.

Summary

What resharper offers as a simple ‘language usage’ opportunity, is actually more than that. It is a performance improvement opportunity. To identify such areas in your code, simply download resharper and use it to Inspect ‘code issues’ as shown in the screenshot below.

 

resharper

Anuj holds professional certifications in Google Cloud, AWS as well as certifications in Docker and App Performance Tools such as New Relic. He specializes in Cloud Security, Data Encryption and Container Technologies.

Initial Consultation

Anuj Varma – who has written posts on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.