Which method is faster?
조회 수: 6 (최근 30일)
이전 댓글 표시
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
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
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!