Hi, I was wondering what would be faster when using foreach: an ArrayList ou an Array. At first, would be expected that foreach with an ArrayList would be slower than with an array, and it is a lot slower. But, doesn't foreach see the Array and the ArrayList has a IEnumerable? Whouldnt it be the same in the foreach prespective?
It appears not to be, If I do the same, but pass an IEnumerable to the foreach it is alot faster, in this case the foreach with the ArrayList is faster. The test is in attachement. This were the times: bash-2.05b$ mono test.exe foreach list: : 00:00:00.0159550 foreach array: : 00:00:00.0000420 IEnumerable list : 00:00:00.0000830 IEnumerable array : 00:00:00.0001040 Can someonte elaborate on this? I am curious. -- Pedro Santos <www.psantos.net> "Si minor plus est ergo nihil sunt omnia..."
using System; using System.Collections; public class Test { private static ArrayList povoate( int quantity ) { ArrayList array = new ArrayList(); for( int i = 0; i < quantity; ++i ) { array.Add( i + "" ); } return array; } private static void doSomething( IEnumerable e ) { string tmp; foreach( string s in e ) { tmp = s; } } public static void Main( string[] args ) { ArrayList list = povoate(1000); // fazer um clone string[] array = (string[]) ((ArrayList)list.Clone()).ToArray(typeof(string)); // jitar doSomething( new string[] {""} ); string tmp; DateTime t1 = DateTime.Now; foreach( string s in list ) { tmp = s; } DateTime t2 = DateTime.Now; foreach( string s in array ) { tmp = s; } DateTime t3 = DateTime.Now; doSomething( list ); DateTime t4 = DateTime.Now; doSomething( array ); DateTime t5 = DateTime.Now; Console.WriteLine("foreach list: : {0}", t2 - t1); Console.WriteLine("foreach array: : {0}", t3 - t2 ); Console.WriteLine("IEnumerable list : {0}", t4 - t3); Console.WriteLine("IEnumerable array : {0}", t5 - t4); } };
signature.asc
Description: This is a digitally signed message part