Efficiency of TypedArray.getProperty()

조회 수: 2 (최근 30일)
SA
SA 2025년 6월 18일
댓글: SA 2025년 6월 24일
I have small objects (we can assume each objects contains just a bunch of number fields), but potentially many of them, stored in an array, and I'm accessing them from C++ according to the obvious pattern
// myarray is matlab::data::TypedArray<matlab::data::Object>
for(int i = 0; i < n; i++)
{
auto value = matlabPtr->getProperty(myarray, i, "myval");
...
}
This turns out to have complexity . I am guessing Matlab needs to somehow re-examine the whole array just to access the i-th element.
So I try to rewrite it according to the following pattern, avoiding at all cost to call the variant of getProperty which takes an index, and always just taking a property of a single object:
for (auto elemRef = myarray.begin(); elemRef != myarray.end(); ++elemRef)
{
auto value = matlabPtr->getProperty( factory.createScalar(*elemRef), "myval" );
...
}
This is orders of magnitude faster and seems to run in as expected. Although it feels like a bad hack because the individual objects are messy to access.
Finally my question: was there something wrong with the first approach that made it so inefficient? Can it be fixed more naturally than in the second approach? If not, is there anything dangerous or to be aware of in the secocond approach? Can it be recommended as a solution to the inefficiency issue?

답변 (1개)

Abhishek
Abhishek 2025년 6월 24일
This is a known performance characteristic of the MATLAB C++ Data API when working with arrays of ‘matlab::data::Object’. The observed behavior is due to the internal implementation of the ‘getProperty(array, index, name)’ overload, which is not optimized for repeated access in tight loops. The inefficiency arises because this overload performs bounds checking and potentially reconstructs references to objects during each access.
To address this issue, a more efficient and recommended approach is to iterate directly over the object array and use the ‘getProperty(Object, name)’ overload, which is significantly faster:
{
auto value = matlabPtr->getProperty(obj, "myval");
// Process value
}
This method has linear time complexity “O(n)” and avoids the overhead associated with accessing elements via indexed lookup on the array.
Please refer to the official documentation of MATLAB: https://www.mathworks.com/help/releases/R2024b/matlab/matlab-data-array.html
  댓글 수: 1
SA
SA 2025년 6월 24일
The question then is what is the correct, from Matlab's point of view, way to construct "obj" in the C++ code. What I do in my second example also seems excessive.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by