Which method is faster?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
1)
a(1,2).last_index=a(1,2).last_index+1;
a(1,2).multiple_vars(a(1,2).last_index) = value1;
2)
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 commentaire
Adam
le 14 Déc 2016
Modifié(e) : Adam
le 14 Déc 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.
Réponses (1)
Jan
le 14 Déc 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.
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!