Efficiency of TypedArray.getProperty()
1 view (last 30 days)
Show older comments
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?
0 Comments
Answers (1)
Abhishek
on 24 Jun 2025
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
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!