我有关于 File.ReadLines() 和 File.ReadAllLines() 的问题。两者之间有什么区别
他们。我有文本文件,其中包含按行显示的数据。File.ReadAllLines()
返回数组并使用 File.ReadLines().ToArray();
我也可以得到相同的结果。那么这些方法是否存在任何性能差异?
string[] lines = File.ReadLines("C:\\mytxt.txt").ToArray();
或者
string[] lines = File.ReadAllLines("C:\\mytxt.txt");
is there any performance difference related to these methods?
是有区别
File.ReadAllLines()
方法一次读取整个文件并返回 string[] 数组,因此在处理大文件时需要时间并且不推荐,因为用户必须等到整个数组返回。
File.ReadLines()
返回 IEnumerable<string>
而且它不会一次读取整个文件,因此在处理大文件时确实是一个更好的选择。
来自 MSDN :
The ReadLines and ReadAllLines methods differ as follows:
When you use ReadLines, you can start enumerating the collection of strings before
the whole collection is returned; when you use ReadAllLines, you must
wait for the whole array of strings be returned before you can access
the array. Therefore, when you are working with very large files,
ReadLines can be more efficient.
示例 1:File.ReadAllLines()
string[] lines = File.ReadAllLines("C:\\mytxt.txt");
示例 2:File.ReadLines()
foreach (var line in File.ReadLines("C:\\mytxt.txt"))
{
//Do something
}