Categories

Loop speed

My post regarding Brandon's research on foreach - http://richardsiddaway.spaces.live.com/blog/cns!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:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>