在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.
但仍然不是一个可接受的性能,特别是考虑到增加的重新分配开销
有没有办法预分配类数组?关于如何有效管理大量物体的任何想法?
谢谢,
Dani
到了这么晚,但这不是另一种解决方案吗?
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.