Class array property with size validation is SLOW
8 ビュー (過去 30 日間)
古いコメントを表示
Class A has an array property of object of another Class B.
Both classes are handle classes.
In the constructor of A it pre-allocates an array for the property of objects of B.
Inside a method of A there is a loop that creates objects of type B and writes to a single element in the array.
If the array property in class A does not have size validation in the definition the write is very fast. But if the property has a basic size validation the update becomes very slow, and depends on the size of the pre-allocated array.
Some fixed overhead of property validation could be expected, but this is something else. It seems that with the size validation on the property it makes Matlab copy the array on every update or something, since the time now depends on the total size of the array.
Is there a way to understand way this happens? Is it expected?
Top function
clc()
N = 10;
% intialize database with 10k elements
% time will depend on number of elements with the property validation below
m_db = database_t(10e3);
% run the processing and measure time
tic();
for n = 1 : N
fprintf("%d/%d\n", n, N)
m_db.process();
end
t1 = toc()
Class A
classdef database_t < handle
properties
%% Change how property is defined here
% 1. With size validation => SLOW
params (1, :) param_t
% 2. Without size validation => FAST
%params param_t
end
methods
function e = database_t(K)
% pre allocate the array
prealloc = param_t("dummy");
e.params = repmat(prealloc, K, 1);
end
function process(e)
K = 200;
for k = 1 : K
% create new parameter object
p = param_t("abc");
% write parameter
% update single element in array
e.params(1) = p;
end
end
end
end
Class B
classdef param_t < handle
properties
key string
end
methods
function e = param_t(key)
e.key = key;
end
end
end
2 件のコメント
回答 (1 件)
Manikanta Aditya
2024 年 3 月 25 日
Hi,
I feel here the issue is due to MATLAB handles array assignments for properties with size validation. When you specify a size for a property, MATLAB enforces that size constraint by creating a new array each time you modify the property. This involves copying the entire array, which can be slow for large arrays.
When you don’t specify a size for the property, MATLAB can use more efficient methods to modify the array, such as changing a single element in place without copying the entire array. This is why the version without size validation is faster.
You could remove the size validation and add checks in your code to ensure the array is the correct size before you use it. This would give you the speed benefits of no size validation while still ensuring the array is the correct size when it needs to be.
Thanks, Hope it helps!
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Logical についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!