Permissions Calculations are Slow
Took a bit of investigating to find where the slow-down was on most pages, but there ended up being around 50-60ms on some pages just to build simple area bits. This seemed like a lot of time for a small block on the page. It turned out, that a majority of the time (about 70%) was spent just calculating permissions for the areas, which led me to wonder, why permissions calculations were so slow.
Well, there wasn't really any design flaw that accounted for this. A lot of the time was accounted for because of nested loops, method calls within those loops, and repetitive merges. But all of this is actually necessary to make custom permissions cascade in an expected way.
A very small bit of optimization was had by making sure the same permissions weren't calculated more than once (~0.1ms). It turned out that by breaking 1 nested loop into 3 almost identical nested loops could further reduce the time by eliminating some unneeded default values that needed to be merged later (~3ms). Another ~3ms was saved by doing the unthinkable and increasing duplicate code within the loops, rather than using separate methods. And another ~3ms was saved by replacing a recursive method with nested loops (the maximum number of recursions was known). However, this all only brought us down to 45-55ms (1.6ms per permission lookup, down from 2ms), which was not really an acceptable range.
So after a little more refactoring, I decided to cache the output of the calculations for each user for each node by storing the final result in the database. The result was that permission calculation time was reduced by a factor of ~10, and times were reduced accordingly (~15-25ms on the tested code segment where permissions were needed).
This has the most noticeable benefit for guest users, because the initial calculation may never be applied for any given guest.
For this to work correctly though, the cache needs to be erased when:
- a user changes member groups (erase cache for that user)
- an area is re-parented (erase cache for that area's before and after childlists)
- masks for a user are changed (erase cache for that user)
- permissions are updated for guests (erase cache for guests)
- permissions are updated for any users (erase cache for all users)