Optimizing memoization for templates