Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

memory - Copy-on-Write and varargin in MATLAB

MATLAB documentation has the section Avoid Unnecessary Copies of Data in which the following statement can be found:

Copy-on-Write

If a function does not modify an input argument, MATLAB does not make a copy of the values contained in the input variable.

There is no word about varargin in that context. I tried to work out a function capable of monitoring the memory usage without success. So I'm here to ask: does the copy-on-write feature work with varargin?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

varargin is a cell array. When you place an object into a cell array the object isn't really copied but its reference count is increased:

a = [1 2 3];
b = 5;
c = {4, 6};
varargin = {a,b,c};

Here just the reference counts of objects that are pointed to by a, b and c are increased. When you do this:

varargin{1}(2) = 7;

because it wants to write to the object that is pointed to by a, it makes a copy of that array object and sets the second element of the new array to 7. The new array is placed in the first cell of varargin and the reference count of the object that is pointed to by a is decreased. However the MATLAB jit compiler may do more optimizations and it may create the variables in-place and so no cell array is created at all. Another possible optimization may be related to small objects like scalars. They are cheap objects and can be cheaply copied and they possibly don't have a reference count.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...