title: Why is calling system grep slower than matching in Ruby?
body: <p>I'm writing some code that loops through all the .rb files in a project and looks if they reference the <code>DateTime</code> class.  My first attempt looked like this:</p>
  
  
  
  <pre class="lang-rb prettyprint-override"><code>file_names.each do |file_name|
    File.foreach(file_name) do |line|
      return file_name if line.match(/DateTime/)
    end
  end
  </code></pre>
  
  <p>Benchmark results for the algorithm show that it takes about <strong>0.6 seconds to run</strong> through 1100 files, 25 times each. Not bad, but I had the thought that calling out to the system's <code>grep</code> command might be faster. My second attempt looks like this:</p>
  
  <pre class="lang-rb prettyprint-override"><code>file_names.each do |file_name|
    return file_name if system("grep DateTime #{file_name} &gt; /dev/null")
  end
  </code></pre>
  
  <p>This takes <strong>35.6 seconds</strong> to run! Does anyone have any insight into why the second attempt performs so poorly? Is calling the system the slow part or is grep slower than the internal ruby code?</p>