Search code examples
c#streamwriterusing-statement

"using" instruction overhead when writing a file in c#


I need to write two logs in two separate files: one writes 530 chars 30 times per second, the other one 50 chras 60 times per second. I save the data that will be written in two separate variables and write them every n and m frames separately. To write the variables I use:

using (StreamWriter writer = new StreamWriter(newFileName, true))

and then

writer.Write(data)

Now... I know the pros of using "using", but I was wondering: does it have a overhead? Why not declare a StreamWriter at the beginning of the code and use it when needed?


Solution

  • Well, if you need to write data with such speed and such frequency, I would suggest do not use using at all, as using at the end will close and dispose stream object, so on the next request you need to reinitialize and reopen stream, which costs.

    So just open ones and use all along you need it. After dispose it manually.