I am trying to find difference of each items of 2 arrays.
int[] items1 = new int[] {10,20,30,40};
int[] items2 = new int[] {20,50,80,100};
resulting array should be
int[] resultItems = {10, 30, 50, 60 }
as the arrays are having more than 10K items, i am trying to avoid looping for better performance. Is there a better way to handle this using LINQ to avoid performance issues?
Thanks!!!
CodePudding user response:
Use multiple threads. Here's a quick sample of subtracting 10.000.000 integers on a single thread:
int []x = new int[100000000];
int []y = new int[100000000];
int []z = new int[100000000];
Random r = new Random();
for (int i = 0; i < 100000000; i )
{
x[i] = r.Next();
y[i] = r.Next();
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// This code will be replaced
for (int i = 0; i < 100000000; i )
z[i] = y[i] - x[i];
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Console.WriteLine(ts);
This takes roughly 500 milliseconds on my hardware.
Now if I create this class:
public static class Subtractor
{
public static void Subtract(int[] x, int[] y, int[]z, int from, int to)
{
for (int i = from; i < to; i )
z[i] = y[i] - x[i];
}
}
and call it on 5 threads:
int []x = new int[100000000];
int []y = new int[100000000];
int []z = new int[100000000];
Random r = new Random();
for (int i = 0; i < 100000000; i )
{
x[i] = r.Next();
y[i] = r.Next();
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// Use 5 threads instead of a single for loop
Task task1 = Task.Factory.StartNew(() => Subtractor.Subtract(x, y, z, 0, 20000000));
Task task2 = Task.Factory.StartNew(() => Subtractor.Subtract(x, y, z, 20000000, 40000000));
Task task3 = Task.Factory.StartNew(() => Subtractor.Subtract(x, y, z, 40000000, 60000000));
Task task4 = Task.Factory.StartNew(() => Subtractor.Subtract(x, y, z, 60000000, 80000000));
Task task5 = Task.Factory.StartNew(() => Subtractor.Subtract(x, y, z, 80000000, 100000000));
Task.WaitAll(task1, task2, task3, task4, task5);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Console.WriteLine(ts);
It only takes approx 150 milliseconds.
CodePudding user response:
You can use LINQ nice and simple
var resultItems = items1.Zip(items2, (i1, i2) => i2 - i1).ToArray();
LINQ will not really be much different in performance than iterating the arrays simultaneously. A slightly more efficient implementation would pre-size a list.
var resultItems = new List<int>(items1.Length);
resultItems.AddRange(items1.Zip(items2, (i1, i2) => i2 - i1));
CodePudding user response:
Using one of Select
's overload:
var diff = items1.Select((item1, index) => items2[index] - item1).ToArray();