Alex Rivera | Logout

Is MATLAB OOP slow or am I doing something wrong?

Asked 2009-11-07T15:36:43.090
157

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 great to be able to do things like a + b, a == b, a.find( b ) instead of strcat( a b ), strcmp( a, b ), retrieve first element of strfind( a, b ), etc.

The problem: slowdown

I put the above things to use and immediately noticed a drastic slowdown. Am I doing it wrong (which is certainly possible as I have rather limited MATLAB experience), or does MATLAB's OOP just introduce a lot of overhead?

My test case

Here's the simple test I did for string, basically just appending a string and removing the appended part again:

Note: Don't actually write a String class like this in real code! Matlab has a native string array type now, and you should use that instead.

classdef String < handle
  ....
  properties
    stringobj = '';
  end
  function o = plus( o, b )
    o.stringobj = [ o.stringobj b ];
  end
  function n = Length( o )
    n = length( o.stringobj );
  end
  function o = SetLength( o, n )
    o.stringobj = o.stringobj( 1 : n );
  end
end

function atest( a, b ) %plain functions
  n = length( a );
  a = [ a b ];
  a = a( 1 : n );

function btest( a, b ) %OOP
  n = a.Length();
  a = a + b;
  a.SetLength( n );

function RunProfilerLoop( nLoop, fun, varargin )
  profile on;
  for i = 1 : nLoop
    fun( varargin{ : } );
  end
  profile off;
  profile report;

a = 'test';
aString = String( 'test' );
RunProfilerLoop( 1000, @(x,y)atest(x,y), a, 'appendme' );
RunProfilerLoop( 1000, @(x,y)btest(x,y), aString, 'appendme' );

Edit
Report

1 Answer

4

The handle class has an additional overhead from tracking all of references to itself for cleanup purposes.

Try the same experiment without using the handle class and see what your results are.

answered 2009-11-10T21:57:30.110

Your Answer