您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

bubuko 2022/1/25 19:45:09 dotnet 字数 4422 阅读 1027 来源 http://www.bubuko.com/infolist-5-1.html

写了段代码,对比分别用FileStream 的ReadByte和Read读取同一个文件的速度,代码中除了必要读取代码外没有其他业务代码,具体如下 class Program { static void Main(string[] args) { Stopwatch sw = new Stopwatc ...

写了段代码,对比分别用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的速度对比

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


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶