MATLAB classes are slow

Alec Jacobson

May 07, 2014

weblog/

I was surprised to find out just how much overhead object-orient programming is in matlab. Consider this simple class:

classdef SlowWrapper < handle
  properties ( Access = public )
    A = [];
    next = 0;
  end
  methods 
    function this = SlowWrapper(n)
      this.A = zeros(n,1);
    end
    function set_next(this,a)
      this.next = this.next+1;
      this.A(this.next) = a;
    end
  end
end

Then if I call set_next 100000 times like this:

slow_wrapper = SlowWrapper(10e5);
tic;
  for x = 1:numel(slow_wrapper.A)
    slow_wrapper.set_next(x);
  end
toc;

I see:

Elapsed time is 24.575752 seconds.

If instead I used primitives outside of a class and use inline code like this:

A = zeros(10e5,1);
next = 0;
tic;
  for x = 1:numel(A)
    next = next+1;
    A(next) = x;
  end
toc

I see

Elapsed time is 0.095078 seconds.

That's a 258x slow down!

Update: Stupidly it's slightly faster if you use the convention set_next(slow_wrapper,x); instead but only by about a 1.2x improvement.