[Performance Tip]StreamReader Or File.ReadAllLines

在我们使用文件读取时,往往会看到StreamReader或者File.ReadAllLInes这样的方法,有时候我就想这两个有什么差别呢?于是写个小程序比较下

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5: using System.IO;
   6: using System.Diagnostics;
   7:  
   8: namespace PerformanceTips
   9: {
  10:     class Program
  11:     {
  12:         static void Main(string[] args)
  13:         {
  14:             string path = Path.Combine(Environment.CurrentDirectory, "Test.txt");
  15:             Stopwatch sw = new Stopwatch();
  16:             sw.Start();
  17:             using (StreamReader sr = new StreamReader(path))
  18:             {
  19:                 sr.ReadToEnd();
  20:             }
  21:             sw.Stop();
  22:             Console.WriteLine("StreamReader.ReadToEnd(), Time Cost: {0}", sw.ElapsedTicks);
  23:  
  24:             sw.Reset();
  25:             sw.Start();
  26:             File.ReadAllText(path);
  27:             sw.Stop();
  28:             Console.WriteLine("File.ReadAllText(), Time Cost: {0}", sw.ElapsedTicks);
  29:  
  30:             Console.Read();
  31:         }
  32:     }
  33: }

测试环境: Visual Studio 2008 SP1 + .Net 3.5 SP1

test.txt

格式: ASCII

大小: 59KB

结果

image

结果差别比较惊人

去查看下File.ReadAllText的源代码 

   1: public static string ReadAllText(string path)
   2: {
   3:     return ReadAllText(path, Encoding.UTF8);
   4: }
   5:  
   6: public static string ReadAllText(string path, Encoding encoding)
   7: {
   8:     using (StreamReader reader = new StreamReader(path, encoding))
   9:     {
  10:         return reader.ReadToEnd();
  11:     }
  12: }

这下把我搞郁闷了, 都是一样的东西要差距这么大,无奈,给StreamReader加上UTF8

   1: using (StreamReader sr = new StreamReader(path, Encoding.UTF8))
   2:             {
   3:                 sr.ReadToEnd();
   4:             }
   5:             sw.Stop();

结果:

image

这样就比较正常了,然而还是有点差距,我们让打开编译器优化, 将模式改到Release

image

再看结果

image

没有办法了,暂时解释为File.ReadAllLines的方法存在于mscorlib中,默认CLR对存在于该程序集中的调用有优化.

无证据,等日后证明或者推翻

posted on 2008-10-30 01:18 xwang 阅读(...) 评论(...) 编辑 收藏

导航

统计