What other options do we have? You can try to write Async statements in your loop. Depending on what you are trying to do in loop, async functions can be a big winner too.You have another option, you can try to run for and foreach loop in parallel way. That means loop will use multiple Threads. To be able to run loops in parallel, you need .Net 4.0 or above frameworks.
Parallel.ForEach()
Parallel class is in System.Threading.Tasks (mscorlib.dll), You can run a for or foreach loop by using the Parallel class. Here is an example of a parallel foreach loop. I have a large dictionary collection and I want to call the CalculateShipping function to do some calculation for every item of that dictionary in the following example.
public void CalculateLoop(Dictionary<int,SoldItem>sample) { Parallel .ForEach(sample, (t) => { CalculateShipping(t.Value); }); }
// You can use async too
public void CalculateLoop(Dictionary<int,SoldItem>sample) { Parallel .ForEach(sample, async (t) => { await CalculateShipping(t.Value); }); }
Now here, is a real example with timing information for regular and parallel loops. In the following example, I insert 70k JSON objects into Redis with regular loop first then I flush the Redis and insert the same objects by using Parallel loop.
Here is the stats. It took 2 seconds to insert 70k JSON objects into Redis by using regular foreach loop. It didn't even take 1 second to insert the same data to Redis when I used Parallel foreach loop.
No comments:
Post a Comment