Który z nich działa lepiej lub jest bardziej poprawny? Czy lepiej jest utworzyć obiekt z klasy StreamWriter
i używać go często w metodzie, a następnie wyrzucić go? lub czy lepiej jest użyć obiektu z StringBuilder
, a następnie utworzyć obiekt z StreamWriter
i natychmiast go zutylizować?Streamwriter vs StringBuilder
1)
var Write = new StreamWriter(string.Format("{0}{1}{2}", Environment.CurrentDirectory, Path.DirectorySeparatorChar, "Dummy.txt"));
for (int i = 0; i < 100; i++)
{
//Do something include calculation
Write.WriteLine(something);
}
Write.Flush();
Write.Dispose();
2)
var Str = new StringBuilder();
for (int i = 0; i < 100; i++)
{
//Do something include calculation
Str.AppendLine(something);
}
var Write = new StreamWriter(string.Format("{0}{1}{2}", Environment.CurrentDirectory, Path.DirectorySeparatorChar, "Dummy.txt"));
Write.Write(Str);
Write.Flush();
Write.Dispose();
Don” t używaj 'string.Format' na ścieżkach, raczej użyj' Path.Combine (Environment.CurrentDirectory, "Dummy.txt") '. – Alxandr
do natychmiastowego "Disposal" spróbuj dowiedzieć się, jak używać 'using() {}' structure – MethodMan
użyj bloku 'using' ze streamWriters: http://stackoverflow.com/questions/212198/what-is-the-c- ostry-używając-blok-i-dlaczego-powinieneś go użyć – 5uperdan