Testing Day (Loops)...

I've run some tests with FOR, FOREACH and WHILE to know wich one is faster.


I wrote a simple program using System.Diagnostics.Stopwatch to measure elapsed time of each one of the cycles. Each cycle reads from a integer List and adds to a second list.

RESULTS:
1000000 Iterations (average results):
FOR: 19,6015 milliseconds
FOREACH: 26,2376 milliseconds
WHILE: 20,0489 milliseconds

2000000 Iterations (average results):
FOR: 39,5402 milliseconds
FOREACH: 53,9931 milliseconds
WHILE: 45,0472 milliseconds

Always try to use the best solution that provides the best performance.

When working with collections FOREACH is the easiest and sometimes the right one to use, but when working with simple objects it might not be the right decision.

WHILE cycle is very useful when we require a conditional validation but it should not be used in regular iterations.

0 comentários:

Post a Comment