optimize stack of recursive calls