Added memoization functionality.