Comparing performance of growing arrays in MATLAB with and without pre-allocation, in addition to expanding the size in batches.
Refer to this Stack Overflow thread.
There are two version of the tests:
- one that adds columns to a matrix
- one that adds rows to a matrix
Keep in mind that MATLAB stores arrays in column-major order, so it the first variant is expected to be faster.
In recent versions, MATLAB has greatly improved the performance of automatic array growth. This is especially true when growing the arrays along the last dimension.
In fact, the tests show that when adding columns, the performance is very similar with or without preallocation, which is pretty amazing!
Unfortunately adding rows without preallocation is extremely slow. This is where the proposed solution of growing in batches is helpful.
Now when it comes to implementation, it is sadly known that calling methods on OOP objects has a higher overhead than calling regular functions. This explains why the implemented classes are slower than the equivalent inlined code...
In the results below, 50K samples are inserted (each sample is a row/column vector of length 20), with a batch size of 10K for the grow-in-batch solutions. Tests were performed in the latest MATLAB R2014b running on Win8.1 64-bit quad-core machine.
% COLUMNS
>> testDynamicArrayC
ans =
0.0164 % pre-allocated
0.0249 % un-allocated
0.6885 % DynamicArrayC class
0.0597 % batch grow function
% ROWS
>> testDynamicArrayR
ans =
0.0186 % pre-allocated
13.8400 % un-allocated
0.7116 % DynamicArrayC class
0.0610 % batch grow function