Is MATLAB OOP slow or am I doing something wrong?

前端 未结 4 805
礼貌的吻别
礼貌的吻别 2020-11-22 08:50

I\'m experimenting with MATLAB OOP, as a start I mimicked my C++\'s Logger classes and I\'m putting all my string helper functions in a String class, thinking it would be gr

4条回答
  •  醉酒成梦
    2020-11-22 09:03

    Actually no problem with your code but it is a problem with Matlab. I think in it is a kind of playing around to look like. It is nothing than overhead to compile the class code. I have done the test with simple class point (once as handle) and the other (once as value class)

        classdef Pointh < handle
        properties
           X
           Y
        end  
        methods        
            function p = Pointh (x,y)
                p.X = x;
                p.Y = y;
            end        
            function  d = dist(p,p1)
                d = (p.X - p1.X)^2 + (p.Y - p1.Y)^2 ;
            end
    
        end
    end
    

    here is the test

    %handle points 
    ph = Pointh(1,2);
    ph1 = Pointh(2,3);
    
    %values  points 
    p = Pointh(1,2);
    p1 = Pointh(2,3);
    
    % vector points
    pa1 = [1 2 ];
    pa2 = [2 3 ];
    
    %Structur points 
    Ps.X = 1;
    Ps.Y = 2;
    ps1.X = 2;
    ps1.Y = 3;
    
    N = 1000000;
    
    tic
    for i =1:N
        ph.dist(ph1);
    end
    t1 = toc
    
    tic
    for i =1:N
        p.dist(p1);
    end
    t2 = toc
    
    tic
    for i =1:N
        norm(pa1-pa2)^2;
    end
    t3 = toc
    
    tic
    for i =1:N
        (Ps.X-ps1.X)^2+(Ps.Y-ps1.Y)^2;
    end
    t4 = toc
    

    The results t1 =

    12.0212 % Handle

    t2 =

    12.0042 % value

    t3 =

    0.5489  % vector
    

    t4 =

    0.0707 % structure 
    

    Therefore for efficient performance avoid using OOP instead structure is good choice to group variables

提交回复
热议问题