Which method is faster?

6 ビュー (過去 30 日間)
Pramit Biswas
Pramit Biswas 2016 年 12 月 14 日
編集済み: Adam 2016 年 12 月 14 日
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 件のコメント
Adam
Adam 2016 年 12 月 14 日
編集済み: Adam 2016 年 12 月 14 日
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.

サインインしてコメントする。

回答 (1 件)

Jan
Jan 2016 年 12 月 14 日
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.

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by