Reputation: 85
Does specifying the input parameters in a function call in terms of output of other functions affect performance? Would the peak memory usage be affected? Would it be better if I use temporary variables and clear them after each intermediate step has been calculated?
For ex:
g=imfill(imclearborder(imdilate(Inp_img,strel('square',5))),'holes');
or
temp1=imdilate(Inp_img,strel('square',5));
temp1=imclearborder(temp1);
g=imfill(temp1,'holes');
clear temp1
Which would be better in terms of peak memory usage and speed?
Upvotes: 2
Views: 199
Reputation: 22255
This isn't an answer to the question you asked as far as the 'letter of the law' is concerned 'per se', (and apologies if I'm making assumptions) but as far as the 'spirit of the law' is concerned, I understand the implied question to be "does writing things as 'ugly' one-liners ever confer any significant optimisation benefits", to which the answer is most definitely no. Partly due to matlab's lazy evaluation, as rody pointed out above.
So I would prefer the second version, simply because it is more readable. It will not have any penalty on performance as far as I'm aware.
Upvotes: 0
Reputation: 38042
It really depends.
From the top of my head (meaning, I could be wrong):
MATLAB uses a lazy copy-on-write scheme for variable assignment. That means,
a = rand(5);
b = a;
will not create an explicit copy of a
. In essence, b
is just a reference. However, when you issue
b(2) = 4;
the full contents of a
will be copied into a new variable, the location where b
points to is changed to that new copy, and the new contents (4) is written.
The same goes for passing arguments. If you issue
c = myFcn(a, b);
and myFcn
only reads data from a
and b
, these variables are never copied explicitly to the function's workspace. But, if it writes (or otherwise makes changes) to a
or b
, their contents will be copied.
So, in your particular case, I think the peak memory for
r = myFcn( [some computation] )
will be equal to or less than
T = [some computation];
r = myFcn( T );
clear T;
If myFcn
makes no changes to T
, there will be no difference at all (save for more hassle on your part, and the risk of forgetting the clear
).
However, if myFcn
changes T
, a deep copy will be made, so for a moment T
will be in memory twice.
The best way to find out is to profile with memory in mind:
profile -memory
Upvotes: 2