Como: Acelerar a pequenos corpos de Loop

Quando um For() loop tem um corpo pequeno, ele pode executar mais lentamente do que o loop equivalente seqüencial. Desempenho mais lento é causado pela sobrecarga envolvida no particionamento de dados e o custo de invocar um delegado em cada iteração do loop. Para abordar esses cenários, o Partitioner classe fornece o Create método, que permite que você forneça um loop seqüencial para o corpo do delegado, para que o delegado é chamado somente uma vez por partição e, em vez de uma vez por iteração. Para obter mais informações, consulte Partitioners personalizados para PLINQ e TPL.

Exemplo

Imports System.Threading.Tasks
Imports System.Collections.Concurrent

Module PartitionDemo

    Sub Main()
        ' Source must be array or IList.
        Dim source = Enumerable.Range(0, 100000).ToArray()

        ' Partition the entire source array. 
        ' Let the partitioner size the ranges.
        Dim rangePartitioner = Partitioner.Create(0, source.Length)

        Dim results(source.Length - 1) As Double

        ' Loop over the partitions in parallel. The Sub is invoked
        ' once per partition.
        Parallel.ForEach(rangePartitioner, Sub(range, loopState)

                                               ' Loop over each range element without a delegate invocation.
                                               For i As Integer = range.Item1 To range.Item2 - 1
                                                   results(i) = source(i) * Math.PI
                                               Next
                                           End Sub)
        Console.WriteLine("Operation complete. Print results? y/n")
        Dim input As Char = Console.ReadKey().KeyChar
        If input = "y"c Or input = "Y"c Then
            For Each d As Double In results
                Console.Write("{0} ", d)
            Next
        End If

    End Sub
End Module
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {

        // Source must be array or IList.
        var source = Enumerable.Range(0, 100000).ToArray();

        // Partition the entire source array.
        var rangePartitioner = Partitioner.Create(0, source.Length);

        double[] results = new double[source.Length];

        // Loop over the partitions in parallel.
        Parallel.ForEach(rangePartitioner, (range, loopState) =>
        {
            // Loop over each range element without a delegate invocation.
            for (int i = range.Item1; i < range.Item2; i++)
            {
                results[i] = source[i] * Math.PI;
            }
        });

        Console.WriteLine("Operation complete. Print results? y/n");
        char input = Console.ReadKey().KeyChar;
        if (input == 'y' || input == 'Y')
        {
            foreach(double d in results)
            {
                Console.Write("{0} ", d);
            }           
        }
    }
}

A abordagem demonstrada neste exemplo é útil quando o loop realiza uma quantidade mínima de trabalho. Como o trabalho se torna mais dispendioso, provavelmente receberá o desempenho igual ou melhor usando um For ou ForEach o loop com o padrão partitioner.

Consulte também

Referência

Iterators (guia de programação C#)

Conceitos

Paralelismo de dados (biblioteca paralela de tarefas)

Partitioners personalizados para PLINQ e TPL

Expressões lambda no PLINQ e TPL