2008年12月16日 星期二

try…catch的成本到底有多高

int cout = 10000; 

            Stopwatch stopwatch = new Stopwatch();


            stopwatch.Start();


            for (int i = 0; i < cout; i++)


            {


                Dictionary<string, string> dic = new Dictionary<string, string>();


                    dic.Add("1", "2");


                    if (!dic.ContainsKey("1"))


                    {


                        dic.Add("1", "2");


                    }


            }


            stopwatch.Stop();


            Console.WriteLine(stopwatch.Elapsed);


            stopwatch.Reset();


            stopwatch.Start();


            for (int i = 0; i < cout; i++)


            {


                Dictionary<string, string> dic = new Dictionary<string, string>();


                try


                {


                    dic.Add("1", "2");


                    dic.Add("1", "2");


                }


                catch


                {


                }

            }
stopwatch.Stop();

Console.WriteLine(stopwatch.Elapsed);

Console.ReadKey(true);   //output:

//00:00:00:0122448

//00:00:23.6119347