1

Why the following indexed parallel.foreach is almost twice slow compared with a normal sequential loop ? Is it related to resource contention?

static void Main(string[] args)
{
    var values = Enumerable.Range(0, 100000).Select(v => v+v);
    Stopwatch s = Stopwatch.StartNew();
    //int index = 0;

    //foreach (double value in values)
    //{
    //    Console.WriteLine("{0}:\t{1}", index, value);
    //    index++;
    //}
    Parallel.ForEach(values, (value, pls, index) =>
    {
        Console.WriteLine("{0}:\t{1}", index, value);
        index++;
    });
    Console.WriteLine(s.Elapsed.TotalMilliseconds);
    Console.ReadLine();
}
2
  • One does things one after another on the same thread, the other has to assign the operations to different threads, so you have to deal with the overhead. Commented Sep 22, 2014 at 16:40
  • 1
    You need to have enough work done in each thread to overcome the overhead of creating and managing the threading processes. Simply adding/displaying a number will certainly be slower threaded. Commented Sep 22, 2014 at 16:53

1 Answer 1

14

The Console can only actually perform one Write at a time, so your second version is spending a lot of time creating multiple threads, scheduling work for each of them, and then just having all but one of them sitting around waiting on the others until they're all done. You get all of the overhead of multithreading and none of the benefits, as you're not actually doing any work in parallel.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.