Veverke
Veverke

Reputation: 11338

Is using File.WriteAllText recommended over File.WriteAllLines for large files?

I am outputing a list of strings into a regular text file. These files may eventually be quite large. In other words, I may end up with large lists of strings to be flushed into disk.

I am assuming that it will be performance wise to do it using

File.WriteAllText("myFile.txt", string.Join(Environment.NewLine, myListOfStrings))

over

File.WriteAllLines("myFile.txt", myListOfStrings),

since I will sum up all IO operations to one.

Am I right / will this really impact performance ?


Edit: Performance Analysis

I had barely ever played with VS Performance Analysis tool, but from the output I am getting (I chose Instrumentation over CPU bound since it sounds more conclusive to me to measure how much time did it spend in functions F1, F2...) - for a txt file with 120.000 lines WriteAllText is performing better by consuming some 7% less time to finish.

On the other hand, simply adding console outputs for stopwatch's start/stops shows WriteAllLines finishes in 0.20... seconds while WriteAllText in 0.30...

Upvotes: 2

Views: 3098

Answers (1)

Magnus
Magnus

Reputation: 46909

The benefit with using WriteAllLines is that you don't need to keep the complete string in memory before writing it to disk. Nor do you need to keep a complete materialized collection in memory, but can feed the IEnumerable.

Upvotes: 1

Related Questions