MATLAB: Can I rely completely on the memory management of MATLAB to free up the memory in the C-MEX routine

managementMATLABmemorymxfree

Can I rely completely on the memory management of MATLAB to free up the memory in my C-MEX routine?
MATLAB frees up the memory automatically in C-MEX routines. Do I have to explicitly use the mxFree routine to free up the memory allocated? Is there any advantage of using mxFree over completely relying on the memory management of MATLAB? MATLAB documentation says:
It is a good programming practice to deallocate memory just as soon as you are through using it. Doing so generally makes the entire system run more efficiently.
If the memory management engine of MATLAB is going to free up the memory automatically, why is the use of mxFree more efficient?

Best Answer

If your MEX-routine is small and memory allocation is not done in different scopes, the use of manual memory allocation has no advantage over the automatic memory management. The efficiency of your MEX-routines will be the same even if you do not manually free the memory and rely solely on the memory management utility of MATLAB.
However, if your program is large and you have data manipulation being done in different scopes (for example, functions), opt for manual de-allocation of memory rather than waiting for the complete execution of the program (after which the memory management utility of MATLAB would occur nonetheless). Manual de-allocation makes the job easier for memory management, avoiding the overheads of making a log of all the places where memory is being allocated. For this case, if you are sure that you will not be needing a particular chunk of data, it is advised to de-allocate the memory manually.