title: System.IO.StreamReader vs. Get-Content vs. System.IO.File
body: <p>I have been comparing various ways to quickly read relatively large text documents in Powershell. These files range from 50kb - 200mb. And I need to quickly parse them for specific lines and/or specific strings. </p>
  
  <p>The three common tools to read files (that I am aware of, and without building a C# library of my own) are: System.IO.StreamReader, System.IO.File, and the Powershell Cmdlet Get-Content. </p>
  
  <p>So I wrote a quick little compare script: </p>
  
  <pre><code>$file = Get-Childitem -path "MyLogFile.txt" #This is a 100mb txt file
  
  $t1 = Measure-Command{
      $reader = New-Object System.IO.StreamReader($file)
      $content = $reader.ReadToEnd()
      $reader.Close()
  }
  Write-host "StreamReader time: " + $t1
  
  $t2 = Measure-Command{
      Get-Content $file 
  }
  Write-host "Get-Content time: " + $t2
  
  $t3 = Measure-Command {
      $reader = [System.IO.File]::OpenText($file)
      $content = $reader.ReadToEnd()
      $reader.Close()
  }
  Write-Host "System.IO.File reader time: " + $t3
  </code></pre>
  
  <p>Which produces (with slight variation of course) the following output:</p>
  
  <pre><code>StreamReader time:  + 00:00:00.5493247
  Get-Content time:  + 00:00:07.8424864
  System.IO.File reader time:  + 00:00:00.7988032
  </code></pre>
  
  <p>So it would seem that <code>[System.IO.StreamReader]</code> is the fastest way to "read" a file. </p>
  
  <p><strong>My question is:</strong></p>
  
  <p>Assuming that </p>
  
  <pre><code>[System.IO.File]::OpenText($file)
  $content = $reader.ReadToEnd()
  </code></pre>
  
  <p>Is equivalent (because they both open file streams) to:</p>
  
  <pre><code>$reader = New-Object System.IO.StreamReader($file)
  $content = $reader.ReadToEnd()
  </code></pre>
  
  <p>Then what makes one slightly faster than the other? Running this about 10 times, it seems like <code>[System.IO.StreamReader]</code> is always ~0.2s faster.  </p>
  
  <p><strong>Sources</strong></p>
  
  <ul>
  <li><a href="https://msdn.microsoft.com/en-us/library/system.io.file.opentext(v=vs.110).aspx" rel="noreferrer">MSDN - System.IO.file.OpenText</a></li>
  </ul>