3

Although I read the gas optimization report, I'm not sure why != 0 is better than > 0 for unsigned integer comparison. Example code is below.

require(numOfRotations > 0, "Empty arrays");

3 Answers 3

5

I got an answer. The reason != 0 is better is the absence of DUP1(0X80) and GT(0X11). But this is a regression in gas savings when going from 0.8.12 to 0.8.13.

https://gist.github.com/IllIllI000/bf2c3120f24a69e489f12b3213c06c94

0

!= 0 is better than > 0 for unsigned integer comparison because if you're checking > 0, the comparison will be true because unsigned integers will always be non-negative.

1
  • Your answer applies equally to !=0. It will be always true when I use !=0. I'm just curious why != is more gas efficient. Is there any difference between opcodes? And also there is a problem if it has a minus value when we use != isn't it?
    – Shift_that
    Nov 13, 2022 at 17:16
0

As shown in the picture bellow with the opcodes every comparison cost 3 gas. However I don't see something like LTE(Less-than or Equal comparison), so I am asuming that operations like >=,<= would cost 6 gas because of the two operations LT/GT + EQ = 6 gas. But since you are asking for >, and not >=, in my opinion there is no price difference.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.