0

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 objects? Or does the complier effectively boil this safe code down to effectively doing just that?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
IamIC
  • 17,747
  • 20
  • 91
  • 154
  • 1
    Just FYI: [`KeyValuePair` is a value type](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx), so those aren't "pointers" in the array; they're the values themselves (each consisting of a `TKey` and a `TValue`) -- though, obviously, `TKey` and/or `TValue` could be reference types. – Dan Tao Oct 17 '10 at 19:21
  • Ah, right, KeyValuePair is a struct, not a class. Thanks @Dan. – IamIC Oct 17 '10 at 19:32

2 Answers2

4

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

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.

Pritesh
  • 1,938
  • 7
  • 32
  • 46