I have a question regarding performance. Consider the following code:
test1 = 0;
for k = 1:100000
test1 = testfun(test1);
end
test2 = 0;
for k = 1:100000
test2 = test2+1;
end
which uses the function
function j = testfun(i)
j=i+1;
end
Simply explained, the code does the same calculation twice, the first time using a local subfunction, the second time using a nested subfunction. In the MathWorks documentation there is an article on improving performance, and there it is recommended to use local instead of nested functions (see here). However, when I run the above code, the first part (local function) needs about 50 times longer than the second part (nested function). So I am wondering if I maybe misunderstood something, or if there are other factors which should be considered when deciding between those two options. I kinda suspect that when a simple process is repeated many times, the nested version is more efficient, because in this case calling the local function needs more time compared to actually executing it.
I have a similar situation with a more complex subfunction which I also call many times. It has about 25 lines, but also mostly consists of basic calculations on arrays with about 1-5 entries. So far I have written it down as a nested subfunction and I was wondering if I could improve the performance by instead writing a local function, but the above test-code doesn't give me much hope.
1 Comment
Direct link to this comment
https://la.mathworks.com/matlabcentral/answers/425410-call-subfunction-many-times-nested-or-local#comment_626115
Direct link to this comment
https://la.mathworks.com/matlabcentral/answers/425410-call-subfunction-many-times-nested-or-local#comment_626115
Sign in to comment.