memoization and performance tweaks