fix($compile): Resolve various potential memory leaks (v1.2.x)

This is basically a backport of #9079 to the stable branch.