[BUG Fix scan mem optimization

This fix a wrong result triggered by gh-1794 that happen due to not deterministic optimization.

In fact, I don't understand why this bug happen... But any change to the optimization order fix it and I made it deterministic.

reported by Andy Sarroff