Replace inefficient implementation which resulted in a stack overflow