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

I am running these two console applications on Windows. 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 assume it is C, because I included cstdio and used the standard functions fopen and fprintf .

 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 run the C # program, I immediately see the message โ€œDone!โ€. When I run a C ++ program (which uses standard C functions), it waits at least 2 seconds to complete and show me the message "Done!".

I just played to check their speed, but now I think I donโ€™t know much. Can someone explain this to me?

NOTE. It is not possible to duplicate โ€œWhy is C # faster than C ++?โ€ Because I do not produce any console outputs such as โ€œcoutโ€ or โ€œConsole.Writeline ()โ€. I am only comparing the flow feed mechanism, which does not include any interference that may interrupt the main task of the program.

+6
source share
2 answers

You compare apples and potatoes. Your C / C ++ program does not perform buffering at all. If you used fstream with buffering, your results would be much better: see also this std :: fstream buffering versus manual buffering (why 10x gain with manual buffering)?

+12
source

I don't think this is a suitable way to compare performance between languages.

In any case, c and C # are completely different animals, when the main difference, in my opinion, is that C # is a managed language (there is a CLR that works in the background and works a lot like optimization, etc.), but C is not.

However, as I said, there are too many differences between them to compare here.

0
source

All Articles