So, I recently blogged about the huge penalty for not compiling your LINQ2SQL. This problem is so big that it occurred to us that maybe all of LINQ has the problem. So, time for a simple test. Below is a very simple program that basically generates a list of Ids. In one case, it’s using LINQ, and the other just Plain C#. The code is pretty self explanatory. Here are the results:
Test Performed | Time to Do 100000 iterations |
Using LINQ | 52ms |
Using Simple C# | 35ms |
Well, my fears are put aside. Though LINQ is somewhat slower, for 100,000 iterations, .052 seconds is pretty good. (compared with processing a single not to complicated LINQ2SQL statement for 100,000 iterations would take about 20,000 seconds or 333 hours. Quite a difference to .052 seconds!
Here is the code I ran for my test. Hope this help!
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace LINQTimingInMemory
{
class Program
{
static void Main(string[] args)
{
for (int i=0;i<2;i++)
{
List<int> myList = new List<int>() {1,2,3,4,5,6,7,8,9,6,5,5,5,5,5,5};
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
int iterations = 100000;
for (int t = 0; t < iterations; t++)
{
if (i == 0)
{
var ids = myList.Where(a => a > 5).ToList();
}
else
{
var ids = new List<int>();
foreach (var v in myList)
{
if (v > 5)
{
ids.Add(v);
}
}
}
}
stopWatch.Stop();
int ti = Convert.ToInt32(stopWatch.ElapsedMilliseconds);
Console.WriteLine("time for " + i.ToString() + " " + ti/iterations + " " + ti);
stopWatch.Reset();
}
}
}
}