在 MATLAB 中管理同一类的大量实例的最佳方法是什么?
使用天真的方法会产生糟糕的结果:
classdef Request
properties
num=7;
end
methods
function f=foo(this)
f = this.num + 4;
end
end
end
>> a=[];
>> tic,for i=1:1000 a=[a Request];end;toc
Elapsed time is 5.426852 seconds.
>> tic,for i=1:1000 a=[a Request];end;toc
Elapsed time is 31.261500 seconds.
继承句柄极大地改善了结果:
classdef RequestH < handle
properties
num=7;
end
methods
function f=foo(this)
f = this.num + 4;
end
end
end
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.097472 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.134007 seconds.
>> tic,for i=1:1000 a=[a RequestH];end;toc
Elapsed time is 0.174573 seconds.
但仍然不是可接受的性能,尤其是考虑到不断增加的重新分配开销
有没有办法预分配类数组?关于如何有效管理大量对象的任何想法?
谢谢,
丹妮
最佳答案
这么晚才来,但这不是另一种解决方案吗?
a = Request.empty(1000,0); tic; for i=1:1000, a(i)=Request; end; toc;
Elapsed time is 0.087539 seconds.
或者更好:
a(1000, 1) = Request;
Elapsed time is 0.019755 seconds.
关于performance - MATLAB 类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/276198/