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.
- C#代码优化学习总结(3)
- C#代码优化学习总结(1)
- C#代码优化学习总结(2)
- C#代码精简优化技巧总结
- C#学习总结(3)——代码连接mysql数据库(VS工具)
- Java基础学习总结(99)——Java代码性能优化总结
- C#性能优化总结
- C#性能优化总结
- C#性能优化总结
- C#性能优化总结
- C#性能优化总结
- 代码优化简单总结(1)
- C++代码优化方法总结(转)
- 代码效率优化总结(一)
- 代码效率优化总结(一)
- c++代码优化总结
- c++代码优化总结
- css代码优化总结
- 在Ubuntu Server下搭建LAMP环境
- Swift闭包的简化写法——强大的Swift闭包
- android.view.InflateException
- 有关事件绑定
- [概念]iOS5 strong, weak, unsafe_unretained ARC
- C#代码优化学习总结(3)
- ubuntu14.04.1 安装配置jdk1.7
- select 语句的性能(一)
- 使用WLST创建domain和cluster
- Spring定义区分xml环境配置
- Layer Programming with Quartz Core
- [网络拾遗] 详解IP地址后面斜杠加具体数字
- String、StringBuffer与StringBuilder之间区别
- 使用GameKit实现iOS设备之间的蓝牙通信