根据发布的建议,我进行了更多测试。当在分配的 LHS 和 RHS 中都引用相同的矩阵时,性能似乎会受到影响。
我的理论是 MATLAB 使用内部引用计数/写时复制机制,这会导致整个矩阵在被双方引用时在内部被复制。(这是一个猜测,因为我不知道 MATLAB 内部)。
这是调用函数 885548 次的结果。(这里的区别是 4 倍,而不是我最初发布的 12 倍。每个函数都有额外的函数包装开销,而在我最初的帖子中,我只是总结了各个行)。
交换 1:12.547 秒
 交换 2:14.301 秒
 交换 3:51.739 秒
这是代码:
 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