I have the following code:
public static void PrependEntitiesToFile(string pathToFile)
{
char[] buffer = new char[10000];
FileInfo file = new FileInfo(pathToFile);
string renamedFile = file.FullName + ".orig";
System.IO.File.Move(file.FullName, renamedFile);
using (StreamReader sr = new StreamReader(renamedFile))
using (StreamWriter sw = new StreamWriter(file.FullName, false))
{
string entityDeclaration = "foo";
sw.Write(entityDeclaration);
string strFileContents = string.Empty;
int read;
while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
{
for (int i = 0; i < buffer.Length; i++)
{
strFileContents += buffer[i].ToString();
}
}
sw.Write(strFileContents, 0, strFileContents.Length);
}
System.IO.File.Delete(renamedFile);
}
This code works but its SOOOOO SLOW because I am looping through each character in the buffer array and ToString()-ing it. Imagine how slow it is when its ingesting and duplicating a 823,000 character file.
Is there a way to convert a fully populated buffer to a string and add it at once rather than looping through each character in the array? Or, generically speaking, is there just a faster way to this?
I am so ashamed of this code.
Actually, that’s not why it’s so slow. It’s slow because you’re doing a repeated string concatenation and that’s
O(n^2). You’d see better performance if you used aStringBuilder. You could also just make an array of the characters, and call the constructor ofstringthat takes such an array.But even better, skip the string all together, and just write the buffer out to
sw.