optimized contains function