Hi Nirosh,
I doubt that is the case. The index based iteration on a List<T> or
ArrayList is always faster than IEnumerator based iteration.
Check the code below. It has both index based iteration and IEnumerator
based iteration. Run it for yourself and see the difference.
ArrayList al = new ArrayList();
for(int i = 1;i <= 1000000; i++)
al.Add(i);
long st = DateTime.Now.Ticks;
// Enumerator based iteration
//
//IEnumerator enumu = al.GetEnumerator();
//int pop = 0;
//enumu.MoveNext();
//while(enumu.MoveNext())
//{
//pop = Convert.ToInt32(enumu.Current);
//}
// Index based iteration
//
int length = al.Count;
int pop = 0;
for(int k = 0; k < length; k++)
{
pop = Convert.ToInt32(al[k]);
}
long et = DateTime.Now.Ticks;
Console.WriteLine(pop);
Console.WriteLine("Time: {0}", (et-st)/10000);
I had put pop outside the while/for loop and printing the value after
the
while/for loop, so that C# compiler won't optimize it out.
On my system (1.7 GHz, 1GB RAM) the IEnumerator approach takes an
average
of
100 milliseonds. The index based approach takes an average of 50-60
milliseonds.
--
Regards,
Aditya.P
:
Noting you....
When coming to iteration technique, using index based iteration is
50%-75%
faster compared to iterating using IEnumerator for List<T> or
ArrayList.
this is true only when you are iterating for nothing.. but if you are
to
use
the corresponding object, you need to unbox it. That is when
IEnumerator
or
foreach loop produce much faster effiecient results...
Nirosh.
"Adityanand Pasumarthi"
<
[email protected]>
wrote in message
If you want to iterate through an array of dynamic length use either
List<T>
or ArrayList. I recomend List<T> over ArrayList if you know the type
of
the
objects that you are iterating through, else ArrayList would be
fine.
I prefer List<T> of ArrayList over a Dictionary<T> or Hashtable in
case
you
do not want to search your objects using a key.
When coming to iteration technique, using index based iteration is
50%-75%
faster compared to iterating using IEnumerator for List<T> or
ArrayList.
So make your choice wisely and based on the requirement.
--
Regards,
Aditya.P
:
Hi,
My app needs to potentially store a large number of custom objects
and
be
able to iterate through them quickly. I was wondering which data
structure
would be the most efficient to do this,a hashtable or a generic
list.
Is using enumerators to iterate through the data structure a good
idea?
I'd appreciate any suggesstions or advice,
Thanks
Macca