C # - Moving objects without a placeholder

I was told that using a temporary object is not the most efficient way to replace elements in an array.

For instance:

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

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

I know that with the help of mathematical units you can, but I cannot understand how this will be done with any other type of object.

+4
source share
5 answers

Switching objects with a temporary one is the most correct way to do it. It should be much higher in your priorities than speed. It is quite easy to write fast trash software.

When working with objects, you simply cannot do it differently. And this is completely ineffective. An additional reference variable pointing to an existing object is unlikely to be a problem.

But even with numerical values, most smart methods do not give the correct results at some point.

+5
source

Perhaps 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 it is a single line does not mean that it also does not use a temporary variable. It is simply hidden as a method parameter (the reference to objects[2] copied and passed to the Exchange method), which makes it less obvious.

+2
source

you could do it with Interlocked.Exchange, but that would not be faster than using the temp variable ... not that speed would probably matter for this sorting problem outside of the interview.

+1
source

Every example I can find on the Internet uses this particular method to replace two elements in an array. In fact, if this were what I often did, I would definitely consider a general extension method similar to this example:

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

0
source

The only time you should worry about creating a temporary object, when it is massive, and the time taken to copy the object will be long enough, and if you do it a lot, for example, or if you make a view of 10 thousand elements and move it from 9999 to 1, 1 stage when checking the time, if it should move or not, and then changing it every time will be a leak. However, a more efficient way would be to test all tests and move once.

0
source

All Articles