Optimizations to handle stack overflow and increase speed