Tech Journal Back to Tech Journal

Which is the fastest way in C# to search an array for a value?

Well, I wasn't sure about this, but I was pretty certain it was a for-loop. So I build an array of random integers, excluding the value Int32.MaxValue, and wrote different ways to search the array for Int32.MaxValue. The goal of such a wild-goose chase was to force each method to go over the entire collection. Some of the ways can return the index of the item found, others merely find the item, and the rest only check for the presence of the item.

There are 10,000 integers in the array that was searched, and each search method was executed 100,000 times.

Results:

Assignment = 438
For Loop over data[] = 875
foreach loop over data[] = 875
Array.AsReadOnly and then .Contains on the collection = 1312
Array.AsReadOnly and then .IndexOf on the collection = 1344
Array.FindIndex loop = 5203
Array.Find loop = 5641
Array.Find loop using static predicate = 5656
Source code:
using System;
using System.Collections.Generic;

public class MyClass
{
	private static bool falsePredicate(int i) {
		return false;
	}

	public static void Main()
	{
		const int Len = 10000;
		const int Iterations = 100000;
		int i,j,k;
		
		int[] data = new int[Len];	
		Random r = new Random();
		for (i=0; i(data).Contains(int.MaxValue);
		}
		ticksEnd = Environment.TickCount;
		
		WL("Array.AsReadOnly and then .Contains on the collection = {0}", ticksEnd - ticksBegin);		
		
		////////////////
		
		ticksBegin = Environment.TickCount;
		for (i=0; i(data).IndexOf(int.MaxValue);
		}
		ticksEnd = Environment.TickCount;
		
		WL("Array.AsReadOnly and then .IndexOf on the collection = {0}", ticksEnd - ticksBegin);		
		
		////////////////		

		ticksBegin = Environment.TickCount;
		for (i=0; i(data, new Predicate(delegate(int a) { return false; }));
		}
		ticksEnd = Environment.TickCount;
		
		WL("Array.FindIndex loop = {0}", ticksEnd - ticksBegin);	
		
		////////////////

		ticksBegin = Environment.TickCount;
		for (i=0; i(data, new Predicate(delegate(int a) { return false; }));
		}
		ticksEnd = Environment.TickCount;
		
		WL("Array.Find loop = {0}", ticksEnd - ticksBegin);	
		
		////////////////

		ticksBegin = Environment.TickCount;
		for (i=0; i(data, falsePredicate);
		}
		ticksEnd = Environment.TickCount;
		
		WL("Array.Find loop using static predicate = {0}", ticksEnd - ticksBegin);
	
		RL();
	}
	
	#region Helper methods

	private static void WL(object text, params object[] args)
	{
		Console.WriteLine(text.ToString(), args);	
	}
	
	private static void RL()
	{
		Console.ReadLine();	
	}
	
	private static void Break() 
	{
		System.Diagnostics.Debugger.Break();
	}

	#endregion
}
Last updated on 2009-04-13 02:24:05 -0700, by Shalom Craimer

Back to Tech Journal