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?

2
  • 1
    Just FYI: KeyValuePair<TKey, TValue> is a value type, 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. Commented Oct 17, 2010 at 19:21
  • Ah, right, KeyValuePair is a struct, not a class. Thanks @Dan. Commented Oct 17, 2010 at 19:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Not to mention that with marshalling data across managed/unmanaged boundaries, it will most likely be WORSE.
@Blindy: Wrong; that's only for COM and P/Invoke.
Just asking purely from an "understanding the framework" point of view.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.