When linking a template to a lot of hosts the frontend uses a lot of time and memory. In my test case where I link 1 template (1 LLD rule with 57 templates) to nearly 10k hosts through 3 levels of inheritance the unmodified code runs out of the 2Gig php memory_limit after an hour of 100% cpu load.
With this patch linking completes in less than 10 minutes wall-time (280s user time+ 11s system time) and peaks at little under 80MB memory.
Unlinking completes in 4.5 minutes ( 52s user + 0.6 seconds system time) using 46MB of memory.
Disclaimer: This patch works for me and my use-case. It has not been thoroughly tested.