c# - 为什么文件扩展名会影响写入速度? (C#, 流式编写器)

标签 c# streamwriter

我目前正在测试将文本数据记录到文件中的不同方法的性能。似乎当我多次打开/写入/关闭时,使用的扩展会影响性能。 (.txt 和 .log 快约 7 倍)

使用的代码:

private static void TestWriteSpeed(FileInfo file)
{
    Stopwatch watch = new Stopwatch();
    watch.Start();
    for (int i = 0; i < 5000; i++)
    {
        using (StreamWriter writer = file.AppendText())
        {
            writer.Write("This is a test");
        }
    }
    Console.WriteLine(file.Name + ": " + watch.Elapsed);
}

static void Main(string[] args)
{
    TestWriteSpeed(new FileInfo("abc.txt"));
    TestWriteSpeed(new FileInfo("abc.txt.01564611564"));
    TestWriteSpeed(new FileInfo("abc.01564611564.txt"));
    TestWriteSpeed(new FileInfo("abc.xml"));
    TestWriteSpeed(new FileInfo("abc.xml.01564611564"));
    TestWriteSpeed(new FileInfo("abc.config"));
    TestWriteSpeed(new FileInfo("abc.config.01564611564"));
    TestWriteSpeed(new FileInfo("abc.exe"));
    TestWriteSpeed(new FileInfo("abc.exe.01564611564"));
    TestWriteSpeed(new FileInfo("abc.log"));
    TestWriteSpeed(new FileInfo("abc.log.01564611564"));
    Console.ReadLine();
}

结果:

abc.txt                  00:00:08.3826847  <---
abc.txt.01564611564      00:00:59.7401633
abc.01564611564.txt      00:00:08.0069698  <---
abc.xml                  00:00:58.2031820
abc.xml.01564611564      00:00:59.3956204
abc.config               00:00:58.4861308
abc.config.01564611564   00:01:01.2474287
abc.exe:                 00:01:00.0924401
abc.exe.01564611564      00:01:00.7371805
abc.log                  00:00:08.0009934  <---
abc.log.01564611564      00:00:59.8029448

为什么会这样?

最佳答案

看起来另一个应用程序或进程正在读取或监视正在写入的文件并出于性能原因忽略 .txt 或 .log 文件。

为什么?因为你的一堆代码在我的笔记本电脑上运行时,对所有文件(22 秒)给出相同的结果,没有任何变化。

关于c# - 为什么文件扩展名会影响写入速度? (C#, 流式编写器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3213850/

相关文章:

c# - OpenCVSharp坐标与System.Drawing坐标之间的转换

c# - StringBuilder.ToString() 抛出 OutOfMemoryException

c# - StreamWriter 不创建新文件

c# 如何使用 Microsoft Graph API 获取 Office 365 用户照片

javascript - 将 bootstrap 模态打印为 PDF

c# - 另一个进程正在使用 StreamWriter/StreamReader 文件

c# - 如何在 C# 中读取 é、â 等特殊字符

c# - 使用/不使用相对路径在 C# 中写入文件

c# - 使用 Protocol buffers/Protobuf 的 PInvoke 通用字符串格式

c# - 将图像作为二进制数据写入文本文件 C#