title: Why is this code using strlen heavily 6.5x slower with GCC optimizations enabled?
body: <p>I wanted to benchmark <code>glibc</code>'s <code>strlen</code> function for some reason and found out it apparently performs <em>much</em> slower with optimizations enabled in GCC and I have no idea why.</p>
  
  <p>Here's my code:</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;time.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  
  int main() {
      char *s = calloc(1 &lt;&lt; 20, 1);
      memset(s, 65, 1000000);
      clock_t start = clock();
      for (int i = 0; i &lt; 128; ++i) {
          s[strlen(s)] = 'A';
      }
      clock_t end = clock();
      printf("%lld\n", (long long)(end - start));
      return 0;
  }
  </code></pre>
  
  <p>On my machine it outputs:</p>
  
  <pre><code>$ gcc test.c &amp;&amp; ./a.out
  13336
  $ gcc -O1 test.c &amp;&amp; ./a.out
  199004
  $ gcc -O2 test.c &amp;&amp; ./a.out
  83415
  $ gcc -O3 test.c &amp;&amp; ./a.out
  83415
  </code></pre>
  
  <p>Somehow, enabling optimizations causes it to execute longer.</p>