简体   繁体   中英

Memory size of function handle - MATLAB

One of the fields in my structure is a function handle:

strct.handl=@(arg1,arg2)handl(arg1,arg2,par1,par2)

Now, arg1 and arg2 are defined every time I use the handle, but par1 and par2 are stored when I define the handle. Thus, (correct me if I'm wrong), handle functions like a pointer to par1 and par2.

In either case, my question is how I can see how much space in my memory handle is taking up because it also 'points' to par1 & par2. However, if I use whos('handl') , I will only get the size of the handle, not handle+par1+par2.

Thanks!

When you construct the anonymous function, you are creating a closure (the function captures any variables defined in its outer scope).

You can use the functions method to get the captured workspace of a function handle:

>> a = 1;
>> f = @(x) x+a;
>> S = functions(f)
S = 
     function: '@(x)x+a'
         type: 'anonymous'
         file: ''
    workspace: {[1x1 struct]}
>> S.workspace{1}
ans = 
    a: 1

I just want to address the memory usage issue that @DankMasterDan pointed out; MATLAB uses a copy-on-write strategy, so if variables in the enclosing workspace are not changed after being captured, you will not incur additional memory usage.

I wanted to add that that when you use anonymous functions in matlab, not only does it save the input arguments in its workspace, it also saves the ENTIRE workspace it was created in into its workspace.

As, in my case, this led to a huge ballooning of memory usage. Thus, I will revent back to normal handles..!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM