title: What's the fastest way to count the number of words in a string in Perl?
body: <p>I have a few functions that I'm running over a million times on various texts, which means small improvements in these functions translate to big gains overall. Currently, I've noticed that all of my functions which involve word counts take drastically longer to run than everything else, so I'm thinking I want to try doing word count in a different way.</p>
  
  <p>Basically, what my function does is grab a number of objects that have text associated with them, verify that that text doesn't match certain patterns, and then count the number of words in that text. A basic version of the function is:</p>
  
  <pre><code>my $num_words = 0;
  for (my $i=$begin_pos; $i&lt;=$end_pos; $i++) {
     my $text = $self-&gt;_getTextFromNode($i);
     #If it looks like a node full of bogus text, or just a number, remove it.
     if ($text =~ /^\s*\&lt;.*\&gt;\s*$/ &amp;&amp; $begin_pos == $end_pos) { return 0; }
     if ($text =~ /^\s*(?:Page\s*\d+)|http/i &amp;&amp; $begin_pos == $end_pos) { return 0; }
     if ($text =~ /^\s*\d+\s*$/ &amp;&amp; $begin_pos == $end_pos) { return 0; }
     my @text_words = split(/\s+/, $text);
     $num_words += scalar(@text_words);
     if ($num_words &gt; 30) { return 30; }
  }
  return $num_words;
  }
  </code></pre>
  
  <p>I'm doing plenty of text comparisons similar to what I'm doing here elsewhere in my code, so I'm guessing my problem must be with my word counting. Is there a faster way to do it than splitting on <code>\s+</code>? If so, what is it and why is it faster (so I can understand what I'm doing wrong and can apply that knowledge to similar problems later on).</p>