我正在优化一个大型批处理程序的内存使用。最占用内存的是不同的 DataTables。例如,我的 DataTable dataTable
使用了约 260MB 的内存。
如在线程 "What is the memory overhead of storing data in a .NET DataTable?" 的被采纳的答案中所建议的那样,我尝试将相关数据从 DataTable 中移出。这是我的代码:
GC.Collect(); // force the garbage collector to free memory
// First stop point - Total process memory (taskmanager) = 900 MB
List<ExpandoObject> expandoList = new List<ExpandoObject>();
foreach (DataRow dataRow in dataTable.Rows)
{
dynamic expandoItem = new ExpandoObject();
expandoItem.FieldName = dataRow["FieldName"].ToString();
expandoList.Add(expandoItem);
}
// Second stop point - Total process memory (taskmanager) = 1055 MB
dataTable.Clear();
dataTable.Dispose();
dataTable = null;
GC.Collect(); // force the garbage collector to free memory
// Third stop point - Total process memory (taskmanager) = 1081 MB (wtf? even more!)
我使用Clear、Dispose和将其设置为null,因为在以下线程中建议这样做:Datatable.Dispose()会使其从内存中删除吗?。请看停止点的注释以查看该点的内存使用情况。我也尝试过使用
using(DataTable dataTable =...)
,但结果是相同的。我做错了什么吗?或者,有没有更好的方法来缩小DataTable中的数据?