Skip to content

Commit c48c6fe

Browse files
committed
parent: efficiency
1 parent 113e757 commit c48c6fe

File tree

4 files changed

+19
-23
lines changed

4 files changed

+19
-23
lines changed

+stdlib/+java/parent.m

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22

33
p = java.io.File(pth).getParent();
44
if isempty(p)
5-
rn = stdlib.root_name(pth);
6-
if ispc() && ~stdlib.strempty(pth) && ~stdlib.strempty(rn) && startsWith(pth, rn)
7-
p = strcat(rn, filesep);
8-
else
9-
p = ".";
5+
p = ".";
6+
if ispc()
7+
rn = stdlib.root_name(pth);
8+
if strlength(pth) && strlength(rn) && startsWith(pth, rn)
9+
p = strcat(rn, filesep);
10+
end
1011
end
1112
else
1213
p = string(p);

+stdlib/+native/parent.m

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,9 @@
33
pth string
44
end
55

6-
f = fullfile(pth);
6+
p = fileparts(stdlib.drop_slash(pth));
77

8-
i = endsWith(f, ["/", filesep]) & ~strcmp(f, stdlib.root(f));
9-
10-
f(i) = extractBefore(f(i), strlength(f(i)));
11-
12-
p = fileparts(f);
13-
14-
i = stdlib.strempty(p);
8+
i = ~strlength(p);
159
p(i) = ".";
1610

1711
% the ~all(i) is for Windows Matlab < R2025a

+stdlib/+python/parent.m

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
1-
function p = parent(pth)
1+
function par = parent(pth)
22

33
try
4-
p = string(py.str(py.pathlib.Path(pth).parent));
5-
if ispc() && p == stdlib.root_name(pth)
6-
p = p + filesep;
4+
op = py.pathlib.Path(pth);
5+
p = op.parent;
6+
par = string(py.str(p)); % 2x faster than string(op.parents(1))
7+
if ispc() && p == op.drive
8+
par = par + filesep;
79
end
810
catch e
9-
p = "";
10-
warning(e.identifier, "parent(%s) failed: %s", pth, e.message)
11+
par = "";
1112
end
1213

1314
end

+stdlib/parent.m

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616
backend (1,:) string = ["java", "python", "native"]
1717
end
1818

19-
if isscalar(file)
20-
[fun, b] = hbackend(backend, "parent");
19+
[fun, b] = hbackend(backend, "parent");
20+
21+
if isscalar(file) || b == "native"
2122
par = fun(file);
2223
else
23-
b = "native";
24-
par = stdlib.native.parent(file);
24+
par = arrayfun(fun, file);
2525
end
2626

2727
end

0 commit comments

Comments
 (0)