Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
这是我当前用于交换数组中的 2 个 KeyValuePair 对象的交换代码:
KeyValuePair<int, T> t = a[i]; a[i] = a[j]; a[j] = t;
使用不安全的代码并仅仅交换两个对象的指针会有任何速度优势吗?或者编译器是否有效地将这个安全代码归结为有效地做到这一点?
不,不会更快。
这是最糟糕的过早的微优化。
事实上,它会慢几个数量级,因为您需要固定数组(使用fixed关键字)才能获得指向它的指针。
fixed
每个优化都有一个 .Net 指针空间。在您的特定情况下不多,但诸如循环冗余检查之类的东西,指针可以为我们提供更优化的解决方案。