C#代码优化学习总结(3)

来源:互联网 发布:网络上载速度慢 编辑:程序博客网 时间:2024/06/01 07:32

继续代码优化的学习总结

Fact 1: Don’t Prematurely Optimize(不要过早的去优化)

Fact 2: If You’re Not Measuring, You’re Guessing

Fact 3: Good Tools Make All the Difference,PerfView.

Fact 4: It’s All about Allocations

             比如:Boxing(装箱),尽量减少装箱操作。

Example 1: string Methods and Value Type Arguments

          public void Log(int id, int size) 
var s = string.Format("{0}:{1}", id, size); //do something else using s.    }
这其中,Format的参数格式如下:string.Format(String, Object, Object);因而使用这个方法的时候,必然会进行装箱操作。
Fix:var s = id.ToString() + ':' + size.ToString();

Example 2: enum Boxing

public enum Color { Red, Green, Blue }public class BoxingExample      {  private string name; private Color color; public override int GetHashCode() { return name.GetHashCode() ^ color.GetHashCode(); } }
Fix:((int)color).GetHashCode().

Example 3: string Operations

LINQ and Lambdas

Using LINQ and lambdas is a great example of using productive features that might require rewriting code if the code executes a large number of times.

public Symbol FindMatchingSymbol(string name) { return symbols.FirstOrDefault(s => s.Name == name);  }

替换为:

public Symbol FindMatchingSymbol(string name)    foreach (Symbol s in symbols) if (s.Name == name)   return s;   return null; }

Dictionary

在数据量很小的时候,不妨使用List<KeyValuePair<K,V>> 代替Dictionary。

最后,记住:

 Don’t prematurely optimize – be productive and tune when you spot problems.
 Profiles don’t lie – you’re guessing if you’re not measuring.
 Good tools make all the difference – download PerfView and look at the tutorials.
 Allocations are king for app responsiveness – this is where the new compilers’ perf team spent most of their time.

0 0