I'm trying to update the timestamp to the current time on all of the xml files in my directory (recursively). I'm using Mac OSX 10.8.5.
On about 300,000 files, the following echo
command takes 10 seconds:
for file in `find . -name "*.xml"`; do echo >> $file; done
However, the following touch
command takes 10 minutes! :
for file in `find . -name "*.xml"`; do touch $file; done
Why is echo so much faster than touch here?
Best Answer
In bash,
touch
is an external binary, butecho
is a shell builtin:Since
touch
is an external binary, and you invoketouch
once per file, the shell must create 300,000 instances oftouch
, which takes a long time.echo
, however, is a shell builtin, and the execution of shell builtins does not require forking at all. Instead, the current shell does all of the operations and no external processes are created; this is the reason why it is so much faster.Here are two profiles of the shell's operations. You can see that a lot of time is spent cloning new processes when using
touch
. Using/bin/echo
instead of the shell builtin should show a much more comparable result.Using touch
Using echo