I’ve asked around, whilst I was trying to learn how to use LINQ. LINQ is a form of SQL directly in .Net languages, so I can do “select”’s directly on objects in memory. A simple select could be:
List<int> test = new List<int>(); test.Add(1); test.Add(3); test.Add(5); List<int> testnew = (from a in test where a == 5 select a).ToList();
So. The argument was that using LINQ for a general select was faster than using a foreach and ‘manually’ pulling out respective items. I will test this:
static List<int> testlist = new List<int>();
static void Main(string[] args)
{
DateTime b, a;
List<double> regularTimes = new List<double>();
List<double> LINQTimes = new List<double>();
for (int x = 0; x < 1000000; x++)
{
testlist.Add(x * 5);
}
// Select normal
for (int x = 0; x < 1000; x++)
{
b = DateTime.Now; // Before
TestRegular();
a = DateTime.Now; // After
regularTimes.Add((a - b).TotalMilliseconds);
}
Console.WriteLine("Regular Avg.: {0}", regularTimes.Average());
// Select LINQ
for (int x = 0; x < 1000; x++)
{
b = DateTime.Now; // Before
TestLINQ();
a = DateTime.Now; // After
regularTimes.Add((a - b).TotalMilliseconds);
}
Console.WriteLine("LINQ Avg.: {0}", regularTimes.Average());
Console.ReadLine();
}
private static void TestRegular()
{
List<int> newlist = new List<int>();
foreach (int item in testlist)
{
if (item % 2000 == 0) newlist.Add(item);
}
}
private static void TestLINQ()
{
var newlist = (from a in testlist where a % 2000 == 0 select a).ToList();
}
Using this, I make 1000 tests on each method, selecting out of 1 000 000 rows. My results are then shown as the average time in milliseconds it takes to execute the select. Results are followed here on my machine.
Regular Avg.: 81,6416701
LINQ Avg.: 84,3083223
It can be discussed that the difference is so small that it’s insignificant and too affected by other variables such as what my pc was doing when the regular system ran vs. when the LINQ system ran.
I will say that it’s some very genuine criticism, since I’m not able to conclude anything based on my relatively small result set. But based on my result set, I’d say that they’re pretty much even – Regular and LINQ compared.