Calling script from a function is recommended?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Now and then I call script from a function, the purspose is often initialize some constant values that are shared by across the program.
function myfun
initialize_cst
% ...
end
where initialize_cst.m is the script, typically
mycst1 = 1;
mypi = pi
% ....
This seem to "poof" thos constants into the function, and the consencus seems to be avoid (at least that is one of the argument where EVAL is not recommend).
If that is the case JIT should not activated with poofing, and I should see some effect in the runtime.
However I do this test and fail to see any effect
function s = foo()
%a = 1:1e6;
bar() % poof a = 1:1e6;"
s = 0;
for i=1:length(a)
s = s + a(i);
end
end
where bar.m is the poofing script
% bar.m
a = 1:1e6;
What I obtain with tic/toc is
>> tic; for i=1:100, foo(); end, toc
Elapsed time is 0.440625 seconds.
Then if I comment the poofing bar and initialize directly a within the function
>> tic; for i=1:100, foo(); end, toc
Elapsed time is 0.421612 seconds.
The timing seems pretty close to me.
My question is then: is variables poof by script really make more harm?
I also open to otherway to share constants than calling script within function. So please feel free to suggest alternative solution.
0 Commenti
Risposte (2)
Walter Roberson
il 10 Apr 2021
% bar.m
fid = fopen('baz.m', 'w'); fprintf(fid,'beta = 1:1e6;\n'); fclose(fid)
whos
baz();
whos
clearvars
foo()
whos
function s = foo()
baz() % poof beta = 1:1e6;"
whos
s = 0;
for i=1:length(beta)
s = s + beta(i);
end
end
So whos says that beta was poofed into the function workspace, but you cannot take length(beta) because somehow the function beta was invoked instead ?
This is documented behaviour as of a few releases back, an explicit change to the execution engine:
When a function contains a reference to a name that is not defined explicitly (parameter, shared variable, assignment statement in scope), and that name is the name of a function in scope, then at execution time, the name shall refer to the function, even if a variable by the same name is poofed into execution.
Names are bound to functions at parse time now unless the name is in scope referring to a variable, or unless an assignment to the variable is present in the code.
Yes, this does mean that poofing constants in by way of a script is reduced functionality .
4 Commenti
Walter Roberson
il 10 Apr 2021
I wanted to isolate down to just the variable poofing; I did not want to deal with any possible complications about finding bar() as that name conflicts with bar() plot.
Vedere anche
Categorie
Scopri di più su Interactive Control and Callbacks in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!