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

继续代码优化的学习总结

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值