Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of swapping two elements in MATLAB

Purely as an experiment, I'm writing sort functions in MATLAB then running these through the MATLAB profiler. The aspect I find most perplexing is to do with swapping elements.

I've found that the "official" way of swapping two elements in a matrix

self.Data([i1, i2]) = self.Data([i2, i1])

runs much slower than doing it in four lines of code:

e1 = self.Data(i1);
e2 = self.Data(i2);
self.Data(i1) = e2;
self.Data(i2) = e1;

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

Would somebody have an explanation as to why?

like image 351
Andrew Shepherd Avatar asked Feb 02 '09 05:02

Andrew Shepherd


1 Answers

Based on suggestions posted, I've run some more tests. It appears the performance hit comes when the same matrix is referenced in both the LHS and RHS of the assignment.

My theory is that MATLAB uses an internal reference-counting / copy-on-write mechanism, and this is causing the entire matrix to be copied internally when it's referenced on both sides. (This is a guess because I don't know the MATLAB internals).

Here are the results from calling the function 885548 times. (The difference here is times four, not times twelve as I originally posted. Each of the functions have the additional function-wrapping overhead, while in my initial post I just summed up the individual lines).

 swap1: 12.547 s
 swap2: 14.301 s
 swap3: 51.739 s

Here's 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
like image 93
Andrew Shepherd Avatar answered Oct 27 '22 17:10

Andrew Shepherd