Decreased performance of constant variables in MATLAB

I recently profiled some MATLAB code, and I was shocked to see the following in a heavily used function:

5.76  198694   58 persistent CONSTANTS; 
3.44  198694   59 if isempty(CONSTANTS) % initialize CONSTANTS

In other words, MATLAB spent about 9 seconds for calling functions in 198694, declaring constant CONSTANTSand checking if it was initialized. This means 13% of the total time spent on this feature.

Are constant variables really carrying such a significant part of the performance in MATLAB? Or are we doing something terrible here?

UPDATE

@Andrew I tried your sample script, and I am very, very puzzled by the output:

time   calls  line
                6 function has_persistent
6.48  200000    7 persistent CONSTANTS 
1.91  200000    8 if isempty(CONSTANTS) 
                9     CONSTANTS = 42;
               10 end

I tried the bench () command and it showed my car in the middle range of the sample machines. Running 64-bit Ubuntu on an i7 processor with a 4 GB Intel (R) Core processor.

+5
1

Matlab. , . , .

32- Matlab R2009b 3,0 Intel Core 2 QX9650 Windows XP x64. . 5 , .

:

function call_has_persistent
for i = 1:200000
    has_persistent();
end

function has_persistent
persistent CONSTANTS
if isempty(CONSTANTS)
    CONSTANTS = 42;
end

:

  0.89  200000    7 persistent CONSTANTS 
  0.25  200000    8 if isempty(CONSTANTS) 

Matlab, CPU ? CONSTANTS? Matlab bench() ?

. . Matlab-, "": , Matlab, , 200 000 . . Matlab (. MATLAB OOP , - ? ), , .

, Matlab , , "", . call_has_persistent script , , .

+8

All Articles