MATLAB Answers

Which method is faster?

4 views (last 30 days)
Pramit Biswas
Pramit Biswas on 14 Dec 2016
Edited: Adam on 14 Dec 2016
a(1,2).multiple_vars(a(1,2).last_index) = value1;
a(1,2).multiple_vars(end+1) = value1;
basically, I want to know what happens actually behind the call of end.
which is recommended, if I have to store several values based on the last index (without pre-allocation)?

  1 Comment

Adam on 14 Dec 2016
doc tictoc
It is trivial to setup a quick function in which you can test these two and time them for yourself. I do this regularly when I reach a point where I have multiple ways to code something and want to know which is faster. You can also use the profiler for more detailed analysis though in a simple case like this it will not likely tell you much.
As Jan Simon says though, only optimise code within a wider context if it is the cause of a bottleneck. If a piece of code takes 1% of your total run time then even if you speed it up 100-fold you'll still only shave 0.9% off your total.

Sign in to comment.

Answers (1)

Jan on 14 Dec 2016
Both methods are suboptimal, because the iterative growing of an array needs a lot of resources. Compared to the missing pre-allocation, the indexing is negligible.
Behing end there is a function, which replies the length of the given dimension of an array. While x(length(x)) is usually a little bit faster than x(end), accessing a nested struct might take longer in your case. Therefore there is no chance to predict the timings in your program, but you can measure it with the profiler.
The end indexing causes several bugs in the past in complicated expressions. Therefore I prefer the explicit usage of numel and size(., dim). The timing is not the point.
Do not optimize code, which is not the bottleneck of the program. Write clean and clear code and optimize only the most time consuming parts finally. Look for "premature optimization" in the net to get more explanations.


Sign in to comment.



Translated by