sha*_*rad 44 c# readline file.readalllines
我有关于File.ReadLines()和File.ReadAllLines()的查询.它们之间有什么区别.我有文本文件,其中包含行数据.File.ReadAllLines()返回数组和使用File.ReadLines().ToArray();也将得到相同的结果.那么这些方法有任何性能差异吗?
string[] lines = File.ReadLines("C:\\mytxt.txt").ToArray();
Run Code Online (Sandbox Code Playgroud)
要么
string[] lines = File.ReadAllLines("C:\\mytxt.txt");
Run Code Online (Sandbox Code Playgroud)
Sud*_*udi 66
这些方法有任何性能差异吗?
是的,有区别
File.ReadAllLines() 方法一次读取整个文件并返回字符串[]数组,因此在处理大型文件时需要花费时间,因为用户必须等待直到返回整个数组,所以不建议这样做.
File.ReadLines()返回一个IEnumerable<string>并且它不会一次读取整个文件,因此在处理大型文件时它确实是一个更好的选择.
来自MSDN:
ReadLines和ReadAllLines方法的不同之处如下:
使用ReadLines时,可以在返回整个集合之前开始枚举字符串集合; 当您使用ReadAllLines时,必须等待返回整个字符串数组才能访问该数组.因此,当您使用非常大的文件时,ReadLines可以更高效.
例1: File.ReadAllLines()
string[] lines = File.ReadAllLines("C:\\mytxt.txt");
Run Code Online (Sandbox Code Playgroud)
例2: File.ReadLines()
foreach (var line in File.ReadLines("C:\\mytxt.txt"))
{
//Do something
}
Run Code Online (Sandbox Code Playgroud)