Monday, April 25, 2011

ConfigurationManager.AppSettings performance

Кешировать настройки в локальных переменных или нет?

        static void Main(string[] args)
        {
            long N = 1000000;

            Stopwatch sw = new Stopwatch();
            sw.Start();
            string str ;
            for (int i = 0; i < N; i++)
            {
                str = Test;
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);

            sw.Reset();
            sw.Start();
            for (int i = 0; i < N; i++)
            {
                str = Test2;
            }
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            Console.ReadKey();
        }

        public static string Test
        {
            get { return ConfigurationManager.AppSettings["test"]; }
        }

        private static string _test2;
        public static string Test2
        {
            get
            {
                if (string.IsNullOrEmpty(_test2))
                {
                    _test2 = ConfigurationManager.AppSettings["test"];
                }
                return _test2;
            }
        }

Кешированый код работает в 30 раз быстрей.

Labels: ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home