Performance of swapping two elements in MATLAB -


As an experiment, I am writing the sort function in MATLAB and then running through the Matab profiler. I have to deal with the most troubling aspect swapping elements.

I have found that the "official" method of swapping two elements in the matrix

  self.Data ([I1, i2]) = self. The data runs ([i2, i1])  

in four lines of code very slow:

  e1 = self Data (i1); E2 = self.Data (i2); Self. Data (i1) = E2; Self. Data (i2) = E1;  

The total length of time taken by the second example is 12 times lower than the single line of code in the first instance.

Why does anyone have an explanation?

Posted on the basis of suggestions, I have some more tests. It appears that the performance hit occurs when the same matrix is ​​referred to in both LHS and RHS of the assignment.

My theory is that MATLAB uses an internal reference-copy / copy-on-write mechanism, and this is causing the whole matrix to be internally copied when it Referenced on both sides. (This is an estimate because I do not know MATLAB International).

Calling the function 885548 times, the results are here. (This difference is four times here, as I originally posted twelve times, each function has additional function-wrapping overhead, whereas in my initial post I just express individual lines). Swap1: 12.547 s Swap 2: 14.301 s Swap 3: 51.739 s

Here is the code:

  Methods (Access = Public) function swap Swap 1, I1, i2); Swap 2 (self, i1, i2); Swap 3 (self, i1, i2); Self.SwapCount = self.SwapCount + 1; End End Methods (Access = Private) %% Swap 1: Value of Store in Temporary Doubles% This is the best performance% function swap 1 (self, i1, i2) e1 = self.Data (i1); E2 = self.Data (i2); Self. Data (i1) = E2; Self. Data (i2) = E1; End %% Swap 2: Storage value swap in floating matrix% Thousands of slow swaps at self% 1 Swap 2 (Self, I, I, 2) Data ([i1, i2]); Self. Data ([i2, i1]) = m; End %% swap 3: does not use variable for storage% its worst performance% function swap 3 (self, i1, i2) itself Data ([i1, i2]) = self-data ([i2, i1]); End End  

Comments