optimize to perform replace carefully