Programmatically opening and closing files in the Matlab editor results in a memory leak. The following code illustrates the problem:
function TestEditorMemoryLeak(filepaths)
for i = 1 : numel(filepaths)
docobj = matlab.desktop.editor.openDocument(filepaths{i});
disp([num2str(i), ': ', filepaths{i}]);
pause(0.2);
docobj.closeNoPrompt();
end
end
Warning: do not run the above code with a large number of files. Depending on how much Java heap memory is allocated under matlab general settings, it could cause matlab to crash and hang causing loss of command history and matlab settings.
I used the above code on about 1300 files, where each file was not too large - maybe an average of around 50 lines per file. On my system, which has the default 768 MB of Java heap memory allocated, the memory runs out after about a thousand files and matlab hangs badly.
I thought that Java garbage collection might clean up after the function runs, but the 768 MB of memory remains used and never goes back to normal in the Windows task manager.
Increasing the Java heap memory setting appropriately, resolves the issue, but I would like to find a real solution. Is there a way to avoid this memory leak? - For example, a way to tell matlab to clean up every now and then? Would be grateful to anyone who has a solution.