Minimizing the Working Set
In loops where there are multiple filters, apply the cheapest filters first and then the filters that reduce the working set the most. For example, consider the following code fragment, which finds sales of appliances in a specified city.
while iter.next(tran) do if tran.type = Type_Sale and tran.myBranch.myLocation.city = targetCity and tran.myProduct.isAppliance then <do something with tran> endif; endwhile;
In this example, tran.type should be checked first, because it is the cheapest. The tran object must be fetched to evaluate all of the other conditions, so we may as well check the type attribute first. If we did the isAppliance check first, we would have to fetch all of the product objects for the transactions that were not sales. Regardless of how many transactions are sales and how many products are appliances, it will save time to check tran.type first.
Now, assume that:
-
80 percent of transactions are sales
-
15 percent, on average, are likely to be in the target city
-
90 percent of the products are appliances
It pays to check the city first, even though it means fetching the branch and location objects for the non‑appliance products. There are very few non‑appliance products, so the number of extra fetches is small. By contrast, checking for non‑appliance products for all other cities would result in a large number of extra fetches.
It doesn't matter if the filters are conditions of an
This code fragment example is simple and concise, to convey the concept. In the real world, each successive filter may be in another method, another class, or even another schema. It may take a bit of investigation to find all of the filters involved in a single loop.