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 件)
Sean de Wolski
2013 年 7 月 26 日
0 投票
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 件のコメント
Saiful
2013 年 7 月 26 日
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 についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!