I came from a
background where I have written the algorithm which process millions of data;
hence performance always plays an important role. I tried my every bit to
reduce every single bit of time. So, I first started with implementing creating Asynchronous tasks using multi threading, parallel loops etc. It reduces huge amount of time but that was
not enough.
In my code I used
LINQ heavily, so just out of curiosity I thought to check how LINQ works
internally.
LINQ is very easy to implement,
and it saves huge amount of time on building logic. But when you have an
application which is very time sensitive, BE AWARE before using LINQ because:
- LINQ internally uses legacy loops, so if you have chance to reduce your loop counts, LINQ prohibit it.
- LINQ works on object which is heavier than any other primitive data type
x
By removing LINQ,
I was able to reduce huge amount of time.
I have taken below
problem statement to prove my point:
If we list all the
natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The
sum of these multiples is 23.
Find the sum of all
the multiples of 3 or 5 below 1000.
Let’s measure the
performance now:
LINQ :
static void Main(string[]
args)
{
Stopwatch
sw = new Stopwatch();
sw.Start();
int sum
= Enumerable.Range(1, 9999).Where(x => isDivisible(x)).Sum();
sw.Stop();
Console.WriteLine("Linq
: Sum = {0} , Time Taken = {1} " , sum,
sw.Elapsed);
}
public static bool isDivisible(int x)
{
if (x
% 3 == 0 || x % 5 == 0) { return true;
}
else return false;
}
Output: Linq : Sum = 23331668 ,
Time Taken = 00:00:00.0141881
While Loop:
static void Main(string[]
args)
{
Stopwatch
sw = new Stopwatch();
sw.Start();
int sum2
= getSum();
sw.Stop();
Console.WriteLine("Legacy
loop : Sum = {0} , Time Taken = {1} ", sum2, sw.Elapsed);
Console.ReadLine();
}
public static int getSum()
{
int sum
= 0;
int index
= 1;
int range
= 10000;
while (index
< range)
{
//int
fivemult = 5 * index;
if (index
* 3 < range) sum = sum + index * 3;
else break; //loop will end as soon as multiple of three cross 9999
if (index
* 5 < range && (index * 5) % 3 != 0) sum = sum + index * 5;
//else
break;
index++;
}
return sum;
}
Output: Legacy loop : Sum =
23331668 , Time Taken = 00:00:00.0002947
Did you notice the
tremendous time difference in both? So,
choose wisely.
So if you are considering writing code for extremely time sensitive
environment, choose legacy loops over LINQ.
Your working
perspective changes with the type of environment you have worked for.
I will be more than
happy to know your points as well. Let me know what you think 😊
Good one Lalita!
ReplyDeleteThank you Subhasis!!
Delete