(Inspired by the comments for this question)
Why is ls
this much slower than echo *
?
$ time bash -c 'for i in {1..10000}; do ls -f > /dev/null; done'
bash -c 'for i in {1..10000}; do ls -f > /dev/null; done' 7.49s user 5.39s system 108% cpu 11.883 total
$ time bash -c 'for i in {1..10000}; do echo * > /dev/null; done'
bash -c 'for i in {1..10000}; do echo * > /dev/null; done' 0.16s user 0.25s system 98% cpu 0.415 total
I mean, sure, ls
being slightly slower than echo *
makes sense, but this seems ridiculous.
Why would ls
be nearly be the case?
If it has to do with ls
not needing the speed, then there's no reason for yes
to be so fast.
What is ls
doing under the hood that makes it so slow?
(I'm using zsh on Arch Linux, on a laptop. Times are similar on bash. I've also tested on a (Linux Mint) desktop computer with similar results. (There, ls -f
is faster at around 7 seconds, echo *
is still about 0.4 seconds, which is still a ridiculous difference.) On Arch Linux, ls
was also unaliased, but I didn't bother for Mint, and it didn't make a difference anyway.)
echo
is probably using the shell's built-in whilels
is forking a new process each time. Changingecho
to/bin/echo
will cause the script tofork
andexec
that program. That'll give you more of an apples-to-apples comparison. – Andy Dalton May 13 '20 at 03:47echo
andls
are essentially builtins – muru May 13 '20 at 03:55