b3.
b3.

Reputation: 7165

Performance issue using enumerations

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.

Upvotes: 3

Views: 597

Answers (2)

Edric
Edric

Reputation: 25140

In my experience, it's likely to be the MyEnum.FALSE piece that's slow. Whenever I've needed to do anything similar, I extract the enum value first, i.e.

falseVal = MyEnum.FALSE; for ii = 1:N, v(ii) = falseVal; end

That might help at least in part.

Upvotes: 0

Bitwise
Bitwise

Reputation: 7805

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.

Upvotes: 4

Related Questions