3

Just adding getter/setter methods on my program makes my program super slow. Is there any explanation for this?

function set.x(obj,newx)
    obj.x = newx;
end

function x = get.x(obj)
    x = obj.x;             
end

That's how I define them under my handle class. Or have I just not implemented them correctly?

Edit

class definition goes...

classdef sensorlocest < handle

    properties(GetAcess = 'public', SetAccess = 'private')
        sensorId; % sensor id
        X; % true x-coordainate
        Y; % true y-coordinate

        x; % estimate of X
        y; % estimate of Y
    end

    methods
        function sesnors = sensorlocest(x,y)
            if nargin ~= 0
               sesnors(49,1) =  sensorlocest;
               for k = 1:length(sensors)
                   sensors(k).sesnorId = k;
                   sensors(k).X = x.*rand;
                   sensors(k).Y = y.*rand;
               end
        end


        function init(sensors,x,y)
            N = length(sensors);
            for i = 1:N
                sensors(i).x = x.*rand;
                sensors(i).y = y.*rand;
            end
        end

        function set.x(sensors,newx) 
            sensors.x = newx; 
        end 

        function set.y(sensors,newy) 
            sensors.y = newy;              
        end 
    end
end
rethabile
  • 3,029
  • 6
  • 34
  • 68

1 Answers1

2

Nope, you are correct. They indeed have an overhead, check out this thread: Is MATLAB OOP slow or am I doing something wrong?

Community
  • 1
  • 1
Andrey Rubshtein
  • 20,795
  • 11
  • 69
  • 104
  • so there is nothing i can do about that? – rethabile Aug 27 '12 at 11:06
  • @tman, check out the thread - Matlab2012a seems to be a bit better according to the benchmark. You can also re-design your system such that you have less calls to getters/setters. – Andrey Rubshtein Aug 27 '12 at 11:08
  • @tman: If you don't *need* setter/getter methods, you should simply skip them. If you do need them, you can minimize the number of calls to getter/setters by e.g. calling them outside a loop, or only at the beginning and the end of a method, and storing the content of `x` in a temporary variable in the meantime. – Jonas Aug 27 '12 at 11:16
  • yeah. that seems to add to the problem since i have an object array and thus have to loop through all the objects setting variables. so that causes many calls to the setter method. – rethabile Aug 27 '12 at 11:36
  • @tman, if you have an object array, consider using vectorized `this` instead of multiple calls. – Andrey Rubshtein Aug 27 '12 at 11:52
  • Unless I'm missing something the most recent benchmark was for 2011b, not 2012a. But I checked the release notes and couldn't find any updates relevant to this issue so the two are probably equivalent. – Salain Aug 27 '12 at 12:16
  • 1
    @Andrey, how would i go about using vectorized this? just added on my question edit an example code that keeps the setter method busy. – rethabile Aug 27 '12 at 13:06