title: Why is bash faster than C?
body: <p>Out of curiosity, I did an adhoc benchmark between Bash and C:</p>
  
  <pre><code>#!/bin/sh
  
  for i in `seq 1 10000`; do
      true
  done
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>#include &lt;unistd.h&gt;
  
  int main() {
      char *const argv[] = { "/bin/true", NULL };
  
      for (int i = 0; i &lt; 10000; i++) {
          pid_t pid = fork();
          if (pid == 0) // child
                  execv(argv[0], argv);
  
          int status = 0;
          waitpid(pid, &amp;status, 0);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>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?</p>