I have a requirement to write HTML to the file system and I was wondering if there is any speed boost in converting it to bytes and writing it using a FileStream rather than using the File.WriteAllText() (or a similar text method).
views:
259answers:
3What do you think happens within File.WriteAllText? In the end, it is going to be bytes hitting the disk. That disk is not unlikely to be the slow part in this chain anyway. Unless the data being written is very large, I would not worry about it, and just use the implementation that I felt was most convenient. If you design the code well it will not be a major thing to change later, if needed.
Write the code that is most readable and maintainable first. Then in the future if you have a performance problem, look for the bottle neck.
(I'd be very surprised if the bottle neck turns out to be anything to do with converting the string to a byte array or not. The bottle neck with something like this will be your disk write speed)
File.WriteAllText uses a StreamWriter behind the scenes:
public static void WriteAllText(string path, string contents, Encoding encoding)
{
using (StreamWriter writer = new StreamWriter(path, false, encoding))
{
writer.Write(contents);
}
}
You have a string already, so converting it to a byte array would be pointless, because this is performed inside the StreamWriter.Flush method anyway using its underlying Encoder class. Flush is called by the StreamWriter.Dispose method which the using clause calls. This is a snippet from the source of Flush via reflector:
int count = this.encoder.GetBytes(this.charBuffer, 0, this.charPos, this.byteBuffer, 0, flushEncoder);
You can see it has a charBuffer. That's just a char[] array which it writes to when you perform StreamWriter.Write(string).
So in short, you already have the string, just let the shorter File method perform the cascading calls, as it makes your source slightly more readable. Converting it to a byte array is also not necessary, as I mentioned the StreamWriter does it for you.
If you're getting conversion issues then use Encoding.Unicode as the final parameter in the 3 parameter overload, as File.WriteAllText(string,string) uses UTF8 without a BOM.