optimize matching algorithm