ozgur
ozgur

Reputation: 2719

Why my C# code is faster than my C code?

I am launching these two console applications on Windows OS. Here is my C# code

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. I am assuming it is C because I included cstdio and used standard fopen and fprintf functions.

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!". When I start C++ program (which uses standard C functions) it waits at least 2 seconds to complete and show me the message "Done!".

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()". I am only comparing filestream mechanism which doesn't include any interference of any kind that can interrupt the main task of the program.

Upvotes: 6

Views: 577

Answers (2)

Philip Stuyck
Philip Stuyck

Reputation: 7467

You are comparing apples and potatoes. Your C/C++ program is not doing any buffering at all. 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)?

Upvotes: 12

Felix Av
Felix Av

Reputation: 1254

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.

However as I said, there are too much differences between the two to compare here.

Upvotes: 0

Related Questions