Performance penalty of persistent variables in MATLAB

Recently I 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, over 198694 function calls, declaring the persistent CONSTANTS and checking if it has been initialized. That represents 13% of the total time spent in that function.

Do persistent variables really carry that much of a performance penalty in MATLAB? Or are we doing something terribly wrong here?

UPDATE

@Andrew I tried your sample script and I am very, very perplexed 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 machine in the middle range of the sample machines. Running Ubuntu 64 bits on a Intel(R) Core(TM) i7 CPU, 4GB RAM.

5
задан lindelof 28 September 2010 в 13:18
поделиться