Which of these two assignments is more efficient
1 view (last 30 days)
Show older comments
Please have a look at the function below and let me know which of the sections labelled (1) and (2) is more efficient.
function pw =realtime_func(c)
persistent c_mem;
if isempty(c_mem)
c_mem=zeros(30,1);
end
%%(1) Is this faster
c_mem=[c_mem(2:end);c];
%%(2) or is this faster
c_mem(1)=[];
c_mem(end+1)=c;
% output
pw=hasTrumpCrashedTheEconomyYet(c_mem);
end
1 Comment
KSSV
on 15 Nov 2016
You can run a profiler to check your self or you can use tic, toc to check the timings. By the way is your label (2) working? It will throw error.
Give details, what is c and what you want to do.
Accepted Answer
Jan
on 15 Nov 2016
Most likely method 1 is faster, because 2 must allocate 2 arrays. But Matlab's JIT acceleration might recognize this and optimize the code. So the only reliable answer is to measure it. Use timeit or run a tic toc and a loop with perhaps 1 million iterations.
Note that asking in the forum needs some time also. So you will have to run the faster version trillions of times to get the invested time back. Is this piece of code really the bottleneck of the complete program? If not: Avoid "premature optimization" (search this term in the net in case of doubts).
More Answers (1)
James Tursa
on 15 Nov 2016
Edited: James Tursa
on 15 Nov 2016
Another method to try that might be faster for your application:
%%(3) or is this faster
c_mem(1:end-1)=c_mem(2:end);
c_mem(end)=c;
2 Comments
Jan
on 16 Nov 2016
It seems like [c_mem(2:end);c] creates the vector c_mem(2:end) explicitely and a new vector, when the last element is added. James solution moves the values inside the existing array whithout allocating a new one.
See Also
Categories
Find more on Target Computer Setup in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!