Fix exponential running time in expression optimizer