Do not bother.
No, really. That function, regardless of implementation, basically
screams “if you call me often, your program will exhibit quadratic
or worse time behaviour, so do not do that.”
It is fine for occasional use, but then you would not care about its
efficiency.