場景:性能
若是對某變量進行賦值,是否須要判斷一下,若是相等就不用賦值,這樣會不會提升性能。spa
代碼以下:pwa
1 string a = "1234567890"; 2 string b = "1234567890"; 3 4 long x1=0, x2=0, x3=0; 5 6 Stopwatch w = new Stopwatch(); 7 8 for (int x = 0; x < 10; x++) 9 { 10 w.Reset(); 11 w.Start(); 12 for (int i = 0; i < 100000000; i++) 13 { 14 a = b; 15 } 16 w.Stop(); 17 x1 += w.ElapsedMilliseconds; 18 19 20 21 w.Reset(); 22 w.Start(); 23 for (int i = 0; i < 100000000; i++) 24 { 25 if(a != b) 26 a = b; 27 } 28 w.Stop(); 29 x2 += w.ElapsedMilliseconds; 30 31 32 w.Start(); 33 for (int i = 0; i < 100000000; i++) 34 { 35 if (!a.Equals(b)) 36 a = b; 37 } 38 w.Stop(); 39 x3 += w.ElapsedMilliseconds; 40 } 41 42 System.Diagnostics.Debug.WriteLine(String.Format("直接賦值耗時:{0}ms", x1)); 43 System.Diagnostics.Debug.WriteLine(String.Format("判斷賦值耗時:{0}ms", x2)); 44 System.Diagnostics.Debug.WriteLine(String.Format("判斷賦值2耗時:{0}ms", x3));
運行結果:code
直接賦值耗時:3294ms
判斷賦值耗時:5955ms
判斷賦值2耗時:18244msorm
結論:blog
判斷後嚴重影響性能,因此無需判斷,直接賦值。string