Backport PR #45247 on branch 1.4.x (PERF: find_stack_level)
Backport PR #45247: PERF: find_stack_level
Looks like we have perf issues from find_stack_level(#46874), so I'm backporting this PR from main.  thanks @lithomas1 