MATLAB: Why is that generally perform the same tasks using the function in matlab file is higher than the efficiency of the script file?

efficiency

using script file
clear
tic
n = 1e4;
fcn = cell(1,n);
for ii = 1:n
fcn{ii} = @(x)x+ii;
end
toc
Elapsed time is 3.289260 seconds. then using function file:
function main
clear
tic
n = 1e4;
fcn = cell(1,n);
for ii = 1:n
fcn{ii} = @(x)x+ii;
end
toc
Elapsed time is 0.118427 seconds.

Best Answer

As Matlab's documentations claims, code in functions is improved by the JIT acceleration, while scripts do not profit from this tool, at least not in the same way.
Other details, which can impede the JIT acceleration:
  • eval, assignin and their evil brothers
  • Redefining variables with the same name but different type
  • Calling of external functions, when Matlab cannot be sure if side effects occur