Compartilhar via


Como: Melhorar o desempenho de um loop (Visual Basic)

You can optimize the performance of a loop by using the most efficient data types. For a short loop that does not run many times the difference might be negligible. However, if the loop runs a large number of times, the performance savings could be considerable.

Integer and UInteger are the most efficient types on current platforms. Short, Long, UShort, and ULong are not as efficient, and Decimal is considerably slower. For more information, see Tipos de dados numéricos (Visual Basic).

To optimize the performance of a For...Next loop

  • Use the most efficient data type for the control variable. The following example shows some possible variations on a loop. The absolute timings are dependent on the platform, but the run-time comparisons are still valid.

    For fastest As Integer = 0 to 1000000
        ' Insert statements to execute for each value of fastest.
    Next fastest
    For notAsFast As Long = 0 to 1000000
        ' Insert statements to execute for each value of notAsFast.
    Next notAsFast
    For muchSlower As Decimal = 0 to 1000000
        ' Insert statements to execute for each value of muchSlower.
    Next muchSlower
    

    The first case takes slightly less time to run than the second case. No entanto, Integer pode alça valores somente até 2.147.483.647, e UInteger somente até 4.294.967.295. Os casos de segundo e terceiro podem lidar com valores maiores, pois ambos Long e Decimal aceitar uma grande variedade de inteiros, mas eles são executados mais lentamente. You might have to make a design decision between speed and capacity of the data types you use.

Consulte também

Tarefas

Como: Transferir controle para fora de uma estrutura de controle (Visual Basic)

Como: Executar várias instruções repetidamente (Visual Basic)

Como: executar várias instruções para cada elemento de uma coleção ou matriz (Visual Basic)

Como: Pular para a próxima iteração de um loop (Visual Basic)

Referência

Instrução For...Next (Visual Basic)

Conceitos

Estruturas de loop (Visual Basic)

Outros recursos

Fluxo de controle no Visual Basic