简体   繁体   English

为什么我的C#代码比我的C代码快?

[英]Why my C# code is faster than my C code?

I am launching these two console applications on Windows OS. 我在Windows操作系统上启动这两个控制台应用程序。 Here is my C# code 这是我的C#代码

int lineCount = 0;
StreamWriter writer = new StreamWriter("txt1.txt",true);
for (int i = 0; i < 900; i++)
{
    for (int k = 0; k < 900; k++)
    {
        writer.WriteLine("This is a new line" + lineCount);
        lineCount++;
    }
}

writer.Close();
Console.WriteLine("Done!");
Console.ReadLine();

And here is my C code. 这是我的C代码。 I am assuming it is C because I included cstdio and used standard fopen and fprintf functions. 我假设它是C,因为我包括cstdio并使用标准的fopenfprintf函数。

FILE *file = fopen("text1.txt","a");

for (size_t i = 0; i < 900; i++)
{
    for (size_t k = 0; k < 900; k++)
    {
        fprintf(file, "This is a line\n");
    }
}

fclose(file);
cout << "Done!";

When I start C# program I immediately see the message "Done!". 当我启动C#程序时,我立即看到消息“完成!”。 When I start C++ program (which uses standard C functions) it waits at least 2 seconds to complete and show me the message "Done!". 当我启动C ++程序(使用标准C函数)时,它等待至少2秒钟才能完成,并向我显示消息“完成!”。

I was just playing around to test their speeds, but now I think I don't know lots of things. 我只是在玩耍来测试他们的速度,但现在我觉得我不知道很多东西。 Can somebody explain it to me? 有人可以向我解释一下吗?

NOTE: Not a possible duplicate of "Why is C# running faster than C++? ", because I am not giving any console output such as "cout" or "Console.Writeline()". 注意:不可能重复“为什么C#运行速度比C ++快?”,因为我没有提供任何控制台输出,如“cout”或“Console.Writeline()”。 I am only comparing filestream mechanism which doesn't include any interference of any kind that can interrupt the main task of the program. 我只是比较文件流机制,它不包括任何可以中断程序主要任务的干扰。

You are comparing apples and potatoes. 你正在比较苹果和土豆。 Your C/C++ program is not doing any buffering at all. 您的C / C ++程序根本没有进行任何缓冲。 If you were to use a fstream with buffering your results would be a lot better : See also this std::fstream buffering vs manual buffering (why 10x gain with manual buffering)? 如果你使用带有缓冲的fstream你的结果会好很多:另见std :: fstream缓冲与手动缓冲(为什么10倍的手动缓冲增益)?

I don't think that's an appropriate way to compare performance between languages. 我认为这不是比较语言之间性能的合适方法。

Anyway c and c# are completely different beasts, when the main difference in my opinion is that C# is managed language (there is CLR that runs in the background and does a lot of work like optimization etc.) while C is not. 无论如何c和c#是完全不同的野兽,当我认为主要的区别是C#是托管语言(有CLR在后台运行并做很多工作,如优化等)而C不是。

However as I said, there are too much differences between the two to compare here. 但正如我所说,两者之间存在太多差异,无法在此进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM