.net performance tuning

JB’s dot trace performance profiler is part of its dot ultimate suite(which includes the famous resharper)

the simplest way to use it is to attach to your already running process(the same setting can be reused next time), and check the “collect profiling data from start”, then hit run before the slow performance happens, then take a snapshot as soon as the slowness ends.

then go to the hot spots or just functions list, order by time.

it will give you where the slowness happened, and even system code that ran slow can be dug into who called them.

then you can use https://benchmarkdotnet.org/, a powerful benchmark tool to compare your different versions of implementation.

sample code:

equality in c#

  1. 单个参数的equals 是Object类的虚方法可以在子类中实现override,如果要override,可以调用第三点接口里的具体类型的Equals, 如果不override, 则 a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method.
  2. 两个参数的equals()是个静态工具方法,被有需要的人调用(比如operator override的实现就可以用它)。它的逻辑是先看reference equal, 不行再调用单个参数的equals。这是固定的逻辑,不会被改变。
  3. IEquatable<T>是类型具体的相等,和第一点不同的是不是object,而是具体类型。用途: The IEquatable<T> interface is used by generic collection objects such as Dictionary<TKey,TValue>List<T>, and LinkedList<T> when testing for equality in such methods as ContainsIndexOfLastIndexOf, and Remove. It should be implemented for any object that might be stored in a generic collection.
  4. GetHashCode()也是Object类的虚方法, 用于: A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey,TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

所以比较的实现主要看需要在那些地方比,这些都可以(有可能需要)实现。virtual equals(Ojbect类型的虚方法)和 operator override不和具体的泛型集合类相关,如果自己的代码用泛型集合类,没有直接使用它们,也可以不实现。

await 非 async方法

Task.whenall()不是异步方法,为什么await task.whenall() 可以工作?

http://blog.stephencleary.com/2012/02/async-and-await.html

One important point about awaitables is this: it is the type that is awaitable, not the method returning the type. In other words, you can await the result of an async method that returns Task … because the method returns Task, not because it’s async. So you can also await the result of a non-async method that returns Task

Task类最重要的方法就是GetAwaiter.

碰到await关键字,CompilerService会编译出taskBuilder,async state machine等隐藏的类代码(要看IL+c#) 并使用awaiter的各种方法(比如GetResult())