码迷,mamicode.com
首页 > 数据库 > 详细

C# FileStream 读取大文件时ReadByte和Read的速度对比

时间:2020-06-02 19:13:00      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:class   顺序   png   ogr   info   ++   byte   ISE   操作   

写了段代码,对比分别用FileStream 的ReadByte和Read读取同一个文件的速度,代码中除了必要读取代码外没有其他业务代码,具体如下

    class Program {
        static void Main(string[] args) {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Test2();
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            sw.Restart();
            Console.WriteLine("=============");
            Test1();
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
        public static void Test1() {
            using (FileStream fs = new FileStream("2020-05-24.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                byte val = 0;
                long total = fs.Length;
                int read = 0;
                while (read < total) {
                    val = (byte)fs.ReadByte();
                    read++;
                }
            }
        }
        public static void Test2() {
            using (FileStream fs = new FileStream("2020-05-24.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
                byte[] buffer = new byte[1024 * 1024];
                int b = 1;
                while (b > 0) {
                    b = fs.Read(buffer, 0, buffer.Length);
                }
            }
        }
    }

 

第一次,先执行Test1函数执行ReadByte操作,再执行Test2执行Read,发现Read是ReadByte的近20倍

技术图片

由于可能硬盘本身读取存在缓存机制,我又是连续读取2次,所以我调换了一下执行顺序

第二次,先Test2,再Test1,发现Read依然比ReadByte快,但是明显低于第一次测试的读取速度,猜测是硬盘读取的缓存机制导致的

技术图片

最终得到结果,取他们都作为第一次读取的速度,发现,通过Read读取数据填充缓冲区明显比ReadByte一个一个的读取快很多,快了近10倍

而且硬盘读取确实有缓存机制,后读取明显比先读取快很多

ReadByte

C# FileStream 读取大文件时ReadByte和Read的速度对比

标签:class   顺序   png   ogr   info   ++   byte   ISE   操作   

原文地址:https://www.cnblogs.com/luludongxu/p/13032762.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!