我发现在Matlab中访问属性非常慢。我还没有找到解决方法,但一些基本的想法可以在这里找到:
http://blogs.mathworks.com/loren/2012/03/26/considering-performance-in-object-oriented-matlab-code/。
但是,这篇文章只谈到了避免可怕、糟糕的性能问题。即使是最简单的属性,性能也不尽如人意。
以Mathworks文章中的示例类为例。我进行了小型测试脚本:
clear all
clc
n = 1e5;
result = zeros(1, n);
tic
for i = 1:n
cyl = SimpleCylinder();
cyl.R = i;
cyl.Height = 10;
result(i) = cyl.volume();
end
toc
clear result
tic
cyl = SimpleCylinder();
cyl.R = 1:n;
cyl.Height = 10;
result = cyl.volume();
toc
result = zeros(1, n);
tic
for i = 1:n
result(i) = pi .* i.^2 .* 10;
end
toc
clear result
tic
R = 1:n;
result = pi .* R.^2 .* 10;
toc
通过这些结果:
Elapsed time is 6.141445 seconds.
Elapsed time is 0.006245 seconds.
Elapsed time is 0.002116 seconds.
Elapsed time is 0.000478 seconds.
正如您所看到的,每次属性访问都会减慢速度。尝试进行向量化(一如既往),但即使是简单的for循环在小n的情况下也比向量化的OOP解决方案更快。(在我的PC上,它们在1e7时相当)。
重要信息:Matlab中的OOP很慢!您为每个属性访问付出代价。
对于您的问题:当您调用
myfun2 (inputvar.var1, inputvar.var2, ... etc )
这些值是被复制的。在函数内部,您不再处理类。变量的访问速度很快。但是,如果您传递整个类,则每次访问属性都会变慢。您可以通过将所有属性缓存在局部变量中并使用这些变量来规避这个问题。
如果您修改类以继承自handle,则所有内容都会变得更快,但差异微乎其微。