[英]Clearing the memory associated to a large List
我遵循了這個SO問題中的建議。 它對我不起作用。 這是我的情況以及與之相關的代碼
我的清單很大,里面有204萬個物品。 我將其讀入內存以對其進行排序,然后將其寫入.csv
文件。 我有11個.csv
文件需要閱讀,然后進行排序。 第一次迭代使我的內存使用量剛剛超過1GB。 我嘗試將列表設置為null
。 我嘗試調用List.Clear()
我也嘗試了List.TrimExcess()
。 我也一直在等待GC
做它的事情。 希望它知道沒有讀取或寫入該列表的信息。
這是我正在使用的代碼。 任何建議總是很感激。
foreach (var zone in zones)
{
var filePath = string.Format("outputs/zone-{0}.csv", zone);
var lines = new List<string>();
using (StreamReader reader = new StreamReader(filePath))
{
var headers = reader.ReadLine();
while(! reader.EndOfStream)
{
var line = reader.ReadLine();
lines.Add(line);
}
//sort the file, then rewrite the file into inputs
lines = lines.OrderByDescending(l => l.ElementAt(0)).ThenByDescending(l => l.ElementAt(1)).ToList();
using (StreamWriter writer = new StreamWriter(string.Format("inputs/zone-{0}-sorted.csv", zone)))
{
writer.WriteLine(headers);
writer.Flush();
foreach (var line in lines)
{
writer.WriteLine(line);
writer.Flush();
}
}
lines.Clear();
lines.TrimExcess();
}
}
嘗試將整個內容放入using
:
using (var lines = new List<string>())
{ ... }
盡管我不確定using
s嵌套。
相反,在有行的lines.Clear;
,添加lines = null;
。 那應該鼓勵垃圾收集器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.