Why the performance of following code is degrading when I use threads ?
- by DotNetBeginner
Why the performance of following code is degrading when I use threads ?
**1.Without threads
int[] arr = new int[100000000]; //Array elements - [0][1][2][3]---[100000000-1]
addWithOutThreading(arr); // Time required for this operation - 1.16 sec
Definition for addWithOutThreading
public void addWithOutThreading(int[] arr)
{
UInt64 result = 0;
for (int i = 0; i < 100000000; i++)
{
result = result + Convert.ToUInt64(arr[i]);
}
Console.WriteLine("Addition = " + result.ToString());
}
**2.With threads
int[] arr = new int[100000000];
int part = (100000000 / 4);
UInt64 res1 = 0, res2 = 0, res3 = 0, res4 = 0;
ThreadStart starter1 = delegate
{ addWithThreading(arr, 0, part, ref res1); };
ThreadStart starter2 = delegate
{ addWithThreading(arr, part, part * 2, ref res2); };
ThreadStart starter3 = delegate
{ addWithThreading(arr, part * 2, part * 3, ref res3); };
ThreadStart starter4 = delegate
{ addWithThreading(arr, part * 3, part * 4, ref res4); };
Thread t1 = new Thread(starter1);
Thread t2 = new Thread(starter2);
Thread t3 = new Thread(starter3);
Thread t4 = new Thread(starter4);
t1.Start();
t2.Start();
t3.Start();
t4.Start();
t1.Join();
t2.Join();
t3.Join();
t4.Join();
Console.WriteLine("Addition = "+(res1+res2+res3+res4).ToString());
// Time required for this operation - 1.30 sec
Definition for addWithThreading
public void addWithThreading(int[] arr,int startIndex, int endIndex,ref UInt64 result)
{
for (int i = startIndex; i < endIndex; i++)
{
result = result + Convert.ToUInt64(arr[i]);
}
}