I have read that if the foreach is very simple, the overhead that I get for using the parallel foreach no worth the cost. So I have a simple WPF application to do some tests. I have this code:
//Parallel.Foreach
txtLog.Text = txtLog.Text + "\r\n\r\n\r\nSe inicia el Parallel.Foreach a " + DateTime.Now;
miSw.Restart();
Parallel.ForEach(miLstInt,
(iteradorInt, state) =>
{
if (iteradorInt >= 500000)
{
state.Stop();
}
});
miSw.Stop();
txtLog.Text = txtLog.Text + "\r\nTiempo total del Parallel.Foreach: " + miSw.ElapsedMilliseconds.ToString();
//Forech
txtLog.Text = txtLog.Text + "\r\n\r\nSe inicia el foreach a " + DateTime.Now;
miSw.Restart();
foreach (int i in miLstInt)
{
if (i >= 500000)
{
break;
}
}
miSw.Stop();
txtLog.Text = txtLog.Text + "\r\nTiempo total del foreach: " + miSw.ElapsedMilliseconds.ToString();
I have a button that when I click it, it run the two foreach and show the results in a textBox.
When I run first time, parallel foreach takes about 29ms and foreach about 3ms. But the second time that I run it and the next times, parallel foreach takes 0ms and foreach is between 2 or 3ms, more times 3 than 2, but the results are more stable.
So my doubt is, why is it more slowly the first time but later is faster? should I have to considerate this, if I will run a command many times, although the first time is slower, does it worth the parallel foreach if the next times it will be faster?