How does MATLAB function pass input argument into the function?

I have a class with properties in it (let say the name of the class file is inputvar), and I use it as the input argument for two different functions, which have an exactly the same calculation, but a little bit different code, which I'll explain later.
For the first function (let say the name is myfun1), I wrote the input argument like this: f = myfun1 (inputvar). So every time I want to use variables from the class inside the function, I'll have to call inputvar.var1, inputvar.var2, and etc.
For the second function (myfun2), I wrote each variables from the class in the input argument, so it looks like this: f = myfun2 (inputvar.var1, inputvar.var2, ... etc ). So inside the function, I just have to use var1, var2, and etc, without having to include the name of the class.
After running both functions, I found that myfun2 runs about 50% faster than myfun1 (I used tic-toc). Can someone explain to me exactly why is that?

回答(1 个)

How many times did you run this to get your timing? Run it at least 10x in a for loop to get a convincing timing metric.
I would expect it to be comparable in terms of time as both are passing by reference.

2 个评论

Hey thanks for replying, Sean!
They run for more than 1000 times, and I have redone it several times, so I'm pretty sure that's a correct timing metric.
My thinking is instead of letting the function to locate the variables in the class by itself (this is what happens in myfun1), it would be faster to tell the function exactly which variables to be used (like in myfun2). Does that make sense? But I just don't know how to test that, and if that's a right explanation at all. I don't really understand how does MATLAB function pass by reference though.
I also observed timing differences in this context, with a little difference in the setup.
Passing obj to a method, I timed accessing many times e.g. obj.x within the method in various computations, as well as creating a local copy and working with the copy, e.g.
x_ = obj.x ;
% .. work on x ..
obj.x = x_ ;
and the latter was consistently more efficient.

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Performance and Memory 的更多信息

提问:

2013-7-26

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by