user762305
user762305

Reputation: 41

C# - Swapping objects without a placeholder

I was told that using a temp object was not the most effective way to swap elements in an array.

Such as:

Object[] objects = new Object[10];
// -- Assign the 10 objects some values
var Temp = objects[2];
objects[2] = objects[4];
objects[4] = Temp;

Is it really possible to swap the elements of the array without using another object?

I know that with math units you can but I cannot figure out how this would be done with any other object type.

Upvotes: 4

Views: 12255

Answers (6)

sgnsajgon
sgnsajgon

Reputation: 704

Swapping via deconstruction:

(first, second) = (second, first);

Upvotes: 4

Dan Tao
Dan Tao

Reputation: 128317

It's possible the person who told you this was thinking of something like this:

objects[2] = Interlocked.Exchange(ref objects[4], objects[2]);

Of course, just because this is one line doesn't mean it isn't also using a temporary variable. It's just hidden in the form of a method parameter (the reference to objects[2] is copied and passed to the Exchange method), making it less obvious.

Upvotes: 2

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234414

Swapping objects with a temporary is the most correct way of doing it. That should rank way higher up in your priorities than speed. It's pretty easy to write fast software that ouputs garbage.

When dealing with objects, you just cannot do it differently. And this is not at all inefficient. An extra reference variable that points to an already existing object is hardly going to be a problem.

But even with numerical values, most clever techniques fail to produce correct results at some point.

Upvotes: 7

BugFinder
BugFinder

Reputation: 17858

The only time you should worry about creating a temporary object is when its massive, and the time taken to copy the object will be sufficiently long and if you're doing it a lot, for example, or if youre doing a sort of 10k items, and moving it from 9999 to 1, 1 stage at a time testing if it should move or not, then swapping it each and every time would be a drain. However, a more efficient way would test all the tests and move once.

Upvotes: 0

Yaur
Yaur

Reputation: 7452

you could do it with Interlocked.Exchange but that won't be faster than using a temp variable... not that speed is likely to matter for this sort problem outside of an interview.

Upvotes: 1

Jamiec
Jamiec

Reputation: 136094

Every example I can find online uses exactly this method to swap 2 elements in an array. In fact, if this were something I were doing often I would definately consider a generic extansion method, akin to this example:

http://w3mentor.com/learn/asp-dot-net-c-sharp/c-collections-and-generics/generically-swapping-two-elements-in-array-using-ccsharp/

Upvotes: 0

Related Questions