Performance - GetChildren vs GetBySegment
GetChildren is a decent method that is also cached in the background. But if you have 1000s of children you will get some performance hits. Another good option if you are only searching for a single content item is to use GetBySegment method. This one works well with large amounts of children with excellent performance.
I tried it on folder that has 13000+ children (yes, bad idea) and these were the results when running on local machine
- GetChildren
17.857sforeach (var folder in ContentRepository.GetChildren<ContentFolder>(parent)) { if (folder.Name == customerId) { ... } }
- GetBySegment
0.147svar customerFolder = ContentRepository.GetBySegment(parent, customerId, LanguageSelector.AutoDetect());
So that's a pretty huge performance gain by more than a factor 100. Hope it helps someone out there to pick the right tool for the job.
Few children => GetChildren
Many children => GetBySegment or Episerver Find...
Happy coding everyone!
Thanks for sharing, any suggestion for contentRepository.GetAncestors?
So, is this
GetBySegment(...)
works as a filter byContentId
you passed on (second parameter)?But, if I see the definition here, that is accepting urlSegment as second parameter. What is that? Or do we have overloaded functions for this?
K Khan: Don't think that method will be a problem. Unless you have very very deep tree structure. Have you seen any performance issues with that one?
Praful Jangid: It's a filter but on the url segment yes. Url segment is the part of the url for that page that is visible in browser. For instance, the url segment for this blog post is performance---getchildren as you can see above in the browser. So if you know the url segment (or route segment as it's also called) you can use that to fetch the page.
So for instance, if I'm building this blog on Episerver world and I want get the 2019 folder for blogs and I have this structure
https://world.episerver.com/blogs/Daniel-Ovaska/Dates/2019/3/performance---getchildren/
If I have the parent page with url
https://world.episerver.com/blogs/Daniel-Ovaska/Dates/
I can then use contentRepo.GetBySegment(parent,"2019",LanguageManager.AutoDetect()) to get the page with url
https://world.episerver.com/blogs/Daniel-Ovaska/Dates/2019/
If you are going to use GetBysegment you have to use caution.
I recently filed a bug about it that has been deemed "by design". If GetBySegment doesn't get a match in the provided language it will return a match for any other language it can find. It might not always be the expected or desired behaviour.
Good to know!