Wednesday, February 26, 2014

Parallel.For loop vs simple for loop

Here is the quick intro to Parallel.For loop to enable data parallelism and of-course benefits of same.

Parallel.For can be used when we can execute for loop iterations in parallel. Here source collection is partitioned and threads are assigned to execute actions.

Example:

Data:

string[] strArraly = this.textBox1.Text.Split(' ');  // textbox1 has a string of approx. 400 words.
int[] lenArray = new int[strArraly.Length];

For Loop:

     for (int i = 0; i < strArraly.Length; i++)
     {
         lenArray[i] = GetStringLengh(strArraly[i]);
     }

Parallel.For

     Parallel.For(0, strArraly.Length, i =>
     {
          lenArray[i] = GetStringLengh(strArraly[i]);
     }
     );

Time consuming Method:

       private int GetStringLengh(string str)
      {
          Thread.Sleep(100);
          return str.Length;
      }


Here if we check the time taken by for loop and Parallel.For loop, there is huge difference in both. For is taking around 38 seconds while Parallel For is taking only 6 second to execute all iterations. Thus Parallel.For can be very handy in some situations.


No comments:

Post a Comment