Replace basename with Parameter Expansion in a Bash Loop
Replace $(basename "$p") with ${p##*/} in a loop. Each command substitution forks a process, and the expansion runs inside the shell, so the gap grows with the count.
A script strips the directory from a long list of paths, and it takes seconds for what looks like trivial work.
p=/var/log/app/server.log
TIMEFORMAT='%R s'
time { for i in $(seq 1 2000); do b=$(basename "$p"); done; }
time { for i in $(seq 1 2000); do b=${p##*/}; done; }0.845 s
0.006 s$(basename "$p") starts a subshell and then executes basename, which means a fork and an exec for every path, while ${p##*/} is parameter expansion that never leaves the shell process. The timings above, from 2000 iterations in a container, differ by about two orders of magnitude. The cost of a process is mostly fixed, so the gap shows up whenever the work itself is tiny.
The expansion does not handle a trailing slash or an empty path the way basename does, so use it on clean input or add the cases yourself. For a single call the saving is a millisecond or so and not worth the change. When the paths come from a file, xargs -n1 basename or sed 's|.*/||' is a single process and often enough.