Optimize writeMessage logic.