Based on the suggestions I made, I did some more tests. It seems that a performance hit occurs when the same matrix refers to both LHS and RHS assignments.
My theory is that MATLAB uses an internal mechanism for counting links / copying to a record, and this leads to the fact that the entire matrix is copied internally when it is referenced on both sides. (This is an assumption because I do not know the internals of MATLAB).
Here is the result of calling the function 885548 times. (The difference here is four times, not twelve times, as I wrote. Each of the functions has additional overhead, while in my first message I just summed up individual lines).
swap1: 12.547 s
swap2: 14.301 s
swap3: 51.739 s
Here is the code:
methods (Access = public) function swap(self, i1, i2) swap1(self, i1, i2); swap2(self, i1, i2); swap3(self, i1, i2); self.SwapCount = self.SwapCount + 1; end end methods (Access = private) % % swap1: stores values in temporary doubles % This has the best performance % function swap1(self, i1, i2) e1 = self.Data(i1); e2 = self.Data(i2); self.Data(i1) = e2; self.Data(i2) = e1; end % % swap2: stores values in a temporary matrix % Marginally slower than swap1 % function swap2(self, i1, i2) m = self.Data([i1, i2]); self.Data([i2, i1]) = m; end % % swap3: does not use variables for storage. % This has the worst performance % function swap3(self, i1, i2) self.Data([i1, i2]) = self.Data([i2, i1]); end end
Andrew Shepherd
source share