How to: Improve the Performance of a LoopÂ
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.
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
How to: Run Several Statements Repeatedly
How to: Run Several Statements for Each Element in a Collection or Array
How to: Skip to the Next Iteration of a Loop
Reference
For...Next Statement (Visual Basic)