我的内存问题与我的应用程序嵌套for循环,我无法弄清楚如何改善它。我尝试过使用linq,但我想内部它是一样的,因为内存泄漏仍然存在。优化嵌套循环
编辑:由于我已经被要求,我会提供更多关于我的问题的信息。
我已经得到了所有我在Lucene的文档存储索引的客户(约400.000)的。每个客户可以在一个以上的机构中工作,其中一些客户可以在200-300个机构中工作。
我需要从“全局”顾客指数检索所有我的客户,并建立一个单独的索引,每家机构中,只有包含它可以看到客户。有一些业务规则和安全规则需要应用于每个机构索引,所以现在,我无法为我的所有机构维护单个客户索引。
我的过程是这样的:
int numDocuments = 400000;
// Get a Lucene Index Searcher from an Index Factory
IndexSearcher searcher = SearcherFactory.Instance.GetSearcher(Enums.CUSTOMER);
// Builds a query that gets everything in the index
Query query = QueryHelper.GetEverythingQuery();
Filter filter = new CachingWrapperFilter(new QueryWrapperFilter(query));
// Sorts by Agency Id
SortField sortField = new SortField("AgencyId, SortField.LONG);
Sort sort = new Sort(sortField);
TopDocs documents = searcher.Search(query, filter, numDocuments, sort);
for (int i = 0; i < numDocuments; i++)
{
Document document = searcher.Doc(documents.scoreDocs[i].doc);
// Builds a customer object from the lucene document
Customer customer = new Customer(document);
// If this nested loop is removed, the memory doesn't grow
foreach(Agency agency in customer.Agencies)
{
// Gets a writer from a factory for the agency id.
IndexWriter writer = WriterFactory.Instance.GetWriter(agency.Id);
// Builds an agency-specific document from the customer
Document customerDocument = customer.GetAgencyDocument(agency.Id);
// Adds the document to the agency's lucene index
writer.AddDocument(customerDocument);
}
}
编辑:解决方案
问题是我没有再使用“文档”对象的情况下,在内部循环,而导致我服务的内存使用量不断增长。只需重复使用Document的单个实例即可解决我的问题。
谢谢大家。
这真的取决于你在做什么,这个代码本身是不渗漏。 – 2012-04-16 16:17:53
“使用大量内存”和“内存泄漏”之间存在差异。 – David 2012-04-16 16:18:24
你简化了它太多。 – 2012-04-16 16:19:16