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!