Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is bash faster than C? [closed]

Tags:

c

bash

shell

Out of curiosity, I did an adhoc benchmark between Bash and C:

#!/bin/sh

for i in `seq 1 10000`; do
    true
done

On my machine, this runs in 0.02 seconds. Extremely fast. My understanding is that Bash parses the command and runs fork/exec. Therefore, I expected the following version, in C, to be much faster, since it doesn't need to do any parsing:

#include <unistd.h>

int main() {
    char *const argv[] = { "/bin/true", NULL };

    for (int i = 0; i < 10000; i++) {
        pid_t pid = fork();
        if (pid == 0) // child
                execv(argv[0], argv);

        int status = 0;
        waitpid(pid, &status, 0);
    }

    return 0;
}

To my astonishment, this took about 8 seconds! I figured Bash might be doing some clever optimization, if it had the insight that true was just a no-op and not worth calling at all. So I tried the same experiment with echo -n and sleep 0.0001 and got similar results. The commands are definitely getting called, but Bash doesn't have the fork/exec overhead that C has. Why is Bash so much faster in this case?

like image 969
marshallm Avatar asked Dec 20 '22 08:12

marshallm


1 Answers

true and echo are both Bash builtin commands, so it doesn't need to spawn an external process to run them, making it much faster.

$ type true
true is a shell builtin
$ type echo
echo is a shell builtin
like image 121
interjay Avatar answered Jan 03 '23 16:01

interjay