Поделиться через


How to: Improve the Performance of a 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 Numeric Data Types (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. However, Integer can handle values only up to 2,147,483,647, and UInteger only up to 4,294,967,295. The second and third cases can handle larger values, because both Long and Decimal accept a wider range of integers, but they run more slowly. You might have to make a design decision between speed and capacity of the data types you use.

See Also

Tasks

How to: Transfer Control Out of a Control Structure (Visual Basic)

How to: Run Several Statements Repeatedly (Visual Basic)

How to: Run Several Statements for Each Element in a Collection or Array (Visual Basic)

How to: Skip to the Next Iteration of a Loop (Visual Basic)

Reference

For...Next Statement (Visual Basic)

Concepts

Loop Structures (Visual Basic)

Other Resources

Control Flow in Visual Basic