I suggest you find the logic to skip such an iteration, but if there is no solution in your context, you can get a performance gain with the following code
1) during the Index it is best to put the field you want to iterate in the first field
Document doc = new Document(); Field companyField = new Field(...); doc.Add(companyField); ...
2) then you need to define a FieldSelector like this
class CompanyNameFieldSelector : FieldSelector { public FieldSelectorResult Accept(string fieldName) { return (fieldName == "companyName" ? FieldSelectorResult.LOAD_AND_BREAK : FieldSelectorResult.NO_LOAD); } }
3) Then, when you want to iterate and select this field, you should do something like this
FieldSelector companySelector = new CompanyNameFieldSelector();
The performance above the code is much better than the code that you specified, because it skips reading unnecessary document fields and saves time.
Ehsan source share