Is `cd` being faster than `addpath` a motivation to use it?
One of my answers was recently downvoted for suggesting use of
cd(path_to_toolbox) rather than one of the path tools, such as addpath or
rmpath. Given the fervent criticism I received I must imagine that there
are very good reasons for using the path tools, presumably they are in
some way more robust, especially when code is distributed to other
systems.
Then I decided to clock the performance of cd versus addpath and was
surprised to find the following result. Prior to each trial I cleared the
workspace and created a string array with alternating paths:
clear
clc
p1 = 'c:\MATLAB7\toolbox\symbolic\@sym\';
p2 = matlabroot;
newpath = repmat(' ',100,100);
for ii=1:2:99
newpath(ii,1:length(p1)) = p1;
newpath(ii+1,1:length(p2)) = p2;
end
The I ran either addpath or cd as follows:
tic
for ii=1:100
addpath(newpath(ii,:))
end
toc
Elapsed time is 13.437000 seconds.
tic
for ii=1:100
cd(newpath(ii,:))
end
toc
Elapsed time is 1.078000 seconds.
Any comments on whether there are conditions under which use of cd might
be justified, for instance to set the path to a function (toolbox or
otherwise), are appreciated. While it may be considered sloppy, I have
used cd for many years and while the slowdown can be appreciable if used
repeatedly, I find that if it is not used in highly iterated parts of a
program the slowdown is worth the simplicity it brings to coding. Notably,
addpath is not more complicated to use, but now I seem to have a real
reason to prefer cd: it's actually faster.
No comments:
Post a Comment