Search an Array - Optimal Way


This article is all about the various ways to search for an object in an array of objects and we will compare the time taken by them to find out the optimal way to implement it in our application.

Using For Loop

        public static void ForLoop(Test1[] objTest)
        {
            for (int i = 0; i < objTest.Length; i++)
            {
                if (string.Compare(find,objTest[i].FirstName,true)==0)
                {
                    break;
                }
            }            

        }


In the above example, I have used the default and the very old method to search for an object which matches the condition.

Using Delegates

        
public static void DelegateLoop(Test1[] objTest)
        {
            Test1 FindTest = objTest.ToList().Find(delegate(Test1 dlgTest=
            {
                return(
                    (string.Compare(find, dlgTest.FirstName,true) == 0)
                    );
            });
        }

In the above example, I have used delegates to search for an object which matches the condition. Here we need to convert the array to list before applying delegates.

Using Lambda Expression

        public static void ListLoop(Test1[] objTest)
        {
            Test1 FindTest = objTest.ToList().Find(element => string.Compare(find, element.FirstName, true) == 0);

        }

In the above example I have used lambda expression instead of applying delegates as I shown in my previous example.

Using Lamda Expression (Without Converting to List)

        public static void LambdaLoop(Test1[] objTest)
        {
            Test1 objTestFind = objTest.Single(p => string.Compare(p.FirstName, find, true) == 0);

        }

In the above example, I have used the Single Lambda expression to search for an Item that matches the condition.

Which method is Faster

I have compared the above methods with different counts of records.

Till 10,000 records, For loop is faster than all of the methods.

Below screen shot will show you the time taken by each method till 10,000 records.

array search in C#

Above 10,000 records For loop slows down and the all other method seems to accomplish the search faster.

Below screen shot will show you the time taken by each method - above 10,000 records.

C# array search

Conclusion

Whenever you write a search algorithm, try to validate the time taken with various methods and implement the optimized way in your application.