3

Does MATLAB's optimizer perform common subexpression elimination on MATLAB code? For example:

if max(val) > minVal && max(val) < maxVal
    maxVal = max(val)
end

How often is max(val) evaluated there? Does it make sense to store the intermediate value in a temporary variable (assuming the repeated calculation is expensive) or does MATLAB handle this automatically?

tbleher
  • 1,077
  • 1
  • 9
  • 17

1 Answers1

3

Pretty sure the answer is no to subexpression elimination and yes to storing intermediate values. Example:

>> x = rand(10000, 1);
>> tic;
for i = 1:100000
  y = max(x) + max(x);
end
toc;
Elapsed time is 4.297135 seconds.
>> tic;
for i = 1:100000
  m = max(x);
  y = m + m;
end
toc;
Elapsed time is 1.074672 seconds.

Even built-in operations like + don't seem to be optimised; a similar test showed that

z = (x + x);
y = z + z + z;

is faster than:

y = (x + x) + (x + x) + (x + x);
Richante
  • 4,353
  • 19
  • 23
  • The latter is a different situation. In floating point arithmetic z+... Yields a different result than x+... – angainor Sep 08 '12 at 12:18