Copy on Write in subfunctions

In my last post on Copy on Write, I didn’t talk at all about one very important consequence of the Copy on Write mechanisms.

Usually, when someone is taught about subfunction, a big emphasis is made on carefully considering memory usage. Indeed, in principle, when you pass a variable to a function, in classical C, the subfunction makes a complete local copy of the variable. So if your variables are large, this can be a big problem. That is why the usage of Pointer is recommended.

Now, as I said, the Matlab programmer does not really have the freedom to use Pointer when he calls a subfunction with Data.

BUT, and this is extremely important, the Copy on Write mechanism is still running, even when you pass a variable to a subfunction. So, in essence, the subfunction only and always receive a Pointer. The local copy only happen if this subfunction makes a change to this variable.

Why is this extremely important? Because Matlab is meant to deal with large data  and I would say that around 90% of all Matlab function don’t change the variable that are passed to them so… well it means that Pointers are used everywhere. I am sure you have noticed that even when you pass very large arrays to matlab function, these are still fast AND the memory usage never skyrocket. Now you know why.

function Value=ReturnValue(A)
Value=A(1,1,1);
function Value=ChangeAndReturnValue(A)
A(1,1,1)=0;
Value=A(1,1,1);

In other words, if A is a large matrix, the function ReturnValue will be much much faster than ChangeAndReturnValue.

Related Posts

This entry was posted in Advanced, Optimizing your code. Bookmark the permalink.

Leave a Reply