title: Perl performance hit between two common regex methods for string trimming?
body: <p>So I'm working on a Perl script that does a large amount of processing (nothing too complicated, but <em>lots</em> of it) and decided to do a little benchmark to compare two common methods of trimming strings.</p>
  
  <p>The first method is a quick one-liner:</p>
  
  <pre><code>$word =~ s/^\s+|\s+$//g;
  </code></pre>
  
  <p>The second method is a little longer, but does the same thing:</p>
  
  <pre><code>$word =~ s/^\s+//;
  $word =~ s/\s+$//;
  </code></pre>
  
  <p>For my benchmarks, I had the script read from a file with 40 million lines, trimming each (does nothing other than that).  The average line length is under 20 bytes.  </p>
  
  <p>The first method took on average 87 seconds to complete.<br>
  The second method took on average 27 seconds to complete.<br>
  Doing no processing (just read line, continue) takes an average 16 seconds.  </p>
  
  <p>The first method (first pass) will match either all the leading or trailing whitespace, then remove it, then match and remove the leading/trailing whitespace on the other side.<br>
  The second method matches and removes all leading whitespace, then matches and removes all trailing whitespace.</p>
  
  <p>Maybe I'm in the wrong here, but why would the second method be over 3x faster than the first?  </p>