Speed Up Loops

by Jun 29, 2011

First, compare these two code samples:

$array = 1..10000
Measure-Command { 

  for ($x=0 $x -lt $array.Count $x++) { $array[$x] } 

}

Measure-Command {  

  $length = $array.Count
  for ($x=0 $x -lt $length $x++) { $array[$x] } 

}

 

The second approach is almost five-times faster. So, you should have a close look at the exit condition your "for" loop uses. The simpler it is designed, the faster the code will execute since it needs to be evaluated for each loop iteration.

Twitter This Tip!
ReTweet this Tip!