Lately I have heard from several developers that FindPagesWithCriteria is evil, and should be avoided at all costs. I’ve heard it from different people, in different unrelated cases, and some comments are needed.
Yes, FindPagesWithCriteria can slow down performance on your site. I emphasize “can” because in most cases, the FindPagesWithCriteria is not the reason your site is slow.
The reason is the amount of data you get back from FindPagesWithCriteria!
I recently helped optimize a template that took 17 seconds to render. The FindPagesWithCriteria call took 500ms. The consensus was that FindPagesWithCriteria is bad and needed to go. A run with DotTrace showed us what was really going on. Heavy (and unnecessary) data manipulation on way to many PageData objects.
The code was churning through ~49.000 PageData objects, making writeable clones, and displayed about 50 pages in a list (some times more, mostly less.)
Perhaps the developer had been reading about this in the SDK:
“Performance tip! Try to setup as few criterias as possible for your selection because every criteria will resolve into a database lookup.”
Sure, isolated, this is true (on a good day), but in most cases, getting too much data will hurt performance a lot more than adding more criterias.
The case I mentioned above was rewritten with more criterias, which returned only the pages the list needed, avoiding post filtering and we also stopped making writable clones (which is something you should seldom have to do in lists anyway.) The FindPagesWithCriteria takes less than 100ms now, and rest of the rendering is not worth measuring. It is blazing fast.
Here are some FindPagesWithCriteria guidelines:
- Beware of large results – a big PageDataCollection requires all PageData objects to be fetched from the database and cached.
- Add as many criterias you need to get only the data you need. Filtering in the database is always faster than in your code
- Think ahead. The search you do today might behave quite different a year from now, when you have more data.
- If you need many FindPagesWithCriteria calls in your solution, consider caching (see the cache framework for more information).
- If you need “the last <n> news articles” type of functionality, consider calling FindPagesWithCriteria many times with increasing time span instead of getting all news and then sort + filter.
- Beware of sorting and filtering. Do not add 1000 pages to a NewsList and then set the MaxCount. It will sort all pages and the limit the count in memory. Complete waste of resources.
- Remember to filter the collection for visitors if you’re presenting it outside a list that does that for you. Do not filter if the list does it for you.
FindPagesWithCriteria is not evil. It is very useful and most sites need it. Just beware of what it returns.