Optimize recursive replacement