Reducing function copy overhead

This is something that occurred to me after helping a user in this thread: How to compare run-time of a model when run in MATLAB vs. OCTAVE?

It turned out the user was calling a function in the pattern “x = f (x, y, z)” in order to grow the array x, which led to very poor performance because of multiple copying of array x back and forth. I could improve the performance by eliminating that pattern.

But it occurred to me that perhaps Matlab is recognizing that pattern while parsing and choosing to pass x by reference instead of value to avoid that overhead. I wanted to ask: how easy or difficult is it to make such a change in Octave, and is it desirable? I am not sure yet whether this will help performance or only encourage bad coding practices. Thoughts?

I guess detecting such pattern may not be hard, but modifying directly the original x, passed by reference to f, could lead to very unexpected behaviors: what if an error occurs in f and x has already been partly modified? E.g.

function x = f (x)
  x *= 2
  error ("Nasty")
endfunction

try
  x = 3;
  y = f (x);
catch
  disp (x)
end_try_catch
1 Like

Yeah, there are complications. The function declaration would need to be “x = f (x)” and the calling location be “foo = f (foo)” and there would need to be an unwind-protect equivalent injected by the interpreter.

Probably too difficult to do all that in interpreted code. Maybe it’s a side effect of JIT compiling in Matlab.

The original code that prompted this thought was a very bad anti-pattern that was better eliminated than accommodated.

I noticed that some code executes significantly slower inside a try-catch block in Matlab than outside. Maybe, they detect that and copy arguments instead of passing by reference…