优化List <string>

Alb*_*uez 0 c# arrays list

我对C#有点新意,我遇到了性能问题.在我的程序中,人们导入一个.txt列表,程序会从中列出一个列表; 问题是它消耗了太多内存,导致PC内存不足而崩溃.我想过使用'yield'而没有成功.有任何想法吗?

private List<string> ImportList()
{
    try
    {
        using (var ofd = new OpenFileDialog() { Filter = "Text files (*.txt) | *.txt" })
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
               return File.ReadAllLines(ofd.FileName).ToList();
            }
        }

        return null;
    }
    catch(OutOfMemoryException ex)
    {
        MessageBox.Show("The list is too large. Try using a smaller list or dividing it.", "Warning!");
        return null;

    }
}
Run Code Online (Sandbox Code Playgroud)

Bra*_*ley 5

方法ReadlAllLines返回一个字符串数组,而不是List => File.ReadAllLines方法(String)

我认为你使用ReadLines(),检查这个问题有关ReadLines和ReadlAllLines之间的差异:

这些方法有任何性能差异吗?是,有一点不同

File.ReadAllLines()方法一次读取整个文件并返回字符串[]数组,因此在处理大型文件时需要花费时间,因为用户必须等待直到返回整个数组,所以不建议这样做.

File.ReadLines()返回一个IEnumerable,它不会一次读取整个文件,因此在处理大型文件时它确实是一个更好的选择.

来自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)

Sudhakar Tillapudi的回复

  • 可以说应该将标记问题标记为_duplicate_而不是引用另一个答案 (3认同)