Is there a speed benefit to using unsafe code in .Net to swap objects of complex types?
Here is my current swap code for swapping 2 KeyValuePair objects in an array:
KeyValuePair<int, T> t = a[i];
a[i] = a[j];
a[j] = t;
Would there be any speed advantage to using unsafe code and merely swapping the pointers of the 2 o开发者_如何转开发bjects? Or does the complier effectively boil this safe code down to effectively doing just that?
No, it won't be any faster.
This is premature micro-optimization at its worst.
In fact, it will be orders of magnitude slower, since you'll need to pin the array (using the fixed
keyword) in order to get a pointer to it.
There is a space for .Net pointers in per optimization. Not much in your particular case but stuff like Circular Redundancy Check, pointers can give us more optimum solution.
精彩评论