Monthly Archive


Loop speed

My post regarding Brandon's research on foreach -!43CFA46A74CF3E96!1600.entry started my thinking about the other looping mechanisms.  Was there any speed differences there? Intuitively I thought there probably wasn't much difference but decided to test.

I ran the following four tests.

for($j=0;$j -le 10; $j++){Measure-Command -Expression {for($i=0;$i -le 50000; $i++){$i*9834}}}

for($j=0;$j -le 10; $j++){Measure-Command -Expression {$i=0;while($i -le 50000){$i*9834;$i++}}}

for($j=0;$j -le 10; $j++){Measure-Command -Expression {$i=0;do{$i*9834;$i++}until($i -ge 50000)}}

for($j=0;$j -le 10; $j++){Measure-Command -Expression {$i=0;do{$i*9834;$i++}while($i -lt 50000)}}

I took the output of each run and averaged the results.

for = 198.09ms

while = 199.91ms

do-until = 200.64ms

do-while = 199.09ms

Nothing to write home about there. Looks like you can use the looping construct of your choice and it won't impact your performance.


Share this post :


Technorati Tags: PowerShell

Leave a Reply