filterTipBranches: Use O(n) instead of O(n^2) algorithm.

Fixes JENKINS-5724.

Before, this made slaves run on 100% CPU for days when idle.

This makes it a few thousand times faster for a repo with 500 branches.