I have a for loop in MATLAB (I know, I know – I should be using vectorization but in this particular case it just makes sense to loop) which replaces certain elements of a vector with a value. This vector is a custom enumeration datatype. The replacement is very slow compared to a similar approach with built-in datatypes (see simple test results below). I’d expect some difference but three orders of magnitude seems high. Is this a know issue?
To recreate the issue create the following enumeration:
classdef MyEnum
enumeration
TRUE
FALSE
INDETERMINATE
end
end
Initialize a vector and do some replacement in a loop:
>> v = repmat(MyEnum.TRUE, 100000, 1); >> tic; for ii = 1:length(v); v(ii) = MyEnum.FALSE; end; toc; Elapsed time is 0.824617 seconds.
Compare this with a similar approach using a built-in type:
>> v = true(100000, 1); >> tic; for ii = 1:length(v); v(ii) = false; end; toc; Elapsed time is 0.000950 seconds.
You are adding a method call at each iteration, which in general is a slow operation. In addition, OOP in Matlab is especially inefficient as discussed here. Read the SO question, there are some interesting details including discussion of performance speedups in newer Matlab versions.