[C#][Tips]迴圈中條件語句注意事項

  • 5697
  • 0
  • C#
  • 2010-04-04

[C#][Tips]迴圈中條件語句注意事項

前幾天整理一個以前寫的小程式,忽然發現一個有趣的事情,

關於IF小細節進而影響程式效能,這裡測試紀錄一下。

 

在迴圈中IF避免呼叫返回函示,請使用區域變數替代

寫法一

[STAThread]
        static void Main( string[] args )
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();                 
            for( Int32 i = 0; i < 5; i++ )
            {
               
                
                for( Int32 j = 0; j < 10000000; j++ )
                {
                    if( Getval() > 100 || Islagre( 10 ) )//返回bool和int值
                        break;                           
                }
               
            }
            sw.Stop();
            Console.Write( "平均花費時間:{0}", ( sw.ElapsedMilliseconds/5 ).ToString() );
            Console.ReadLine();
        }
 
        private static Int32 Getval()
        {
            return 99;
        }
 
        private static bool Islagre( Int32 val )
        {
            if( val > 100 )
                return true;
            else
                return false;
        }

 

 

 

 

image

寫法二(使用區域變數替代)

[STAThread]
        static void Main( string[] args )
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();           
            bool getresult = Islagre( 10 );
            Int32 currentval = Getval();
            for( Int32 i = 0; i < 5; i++ )
            {
               
                
                for( Int32 j = 0; j < 10000000; j++ )
                {                
                    if( currentval > 100 || getresult )//區域變數
                        break;                 
                }
               
            }
            sw.Stop();
            Console.Write( "平均花費時間:{0}", ( sw.ElapsedMilliseconds/5 ).ToString() );
            Console.ReadLine();
        }
 
        private static Int32 Getval()
        {
            return 99;
        }
 
        private static bool Islagre( Int32 val )
        {
            if( val > 100 )
                return true;
            else
                return false;
        }

 

 

 

 

image

兩種寫法5次平均時間可以看到相差5倍,以後自己得多多注意了!

範例:mytest.rar