-
Notifications
You must be signed in to change notification settings - Fork 58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conditional statement "!=" is not more gas efficient than ">" or ">=" #23
Comments
Update: this conversation on Twitter is related to this issue. As per transmission11's reply there, it does look like in an older version of Solidity, Tagging @hrkrshnn in case he can illuminate us here? |
I will follow up tomorrow. |
Thanks @hrkrshnn, though no rush from my end. |
@PaulRBerg The main difference is the use of I think these expressions should have the same cost if |
Thanks @hrkrshnn, makes sense. What I don't understand though is that when I compiled the the code snippets above in Remix, I did not enable Is it that in the latest versions of Solidity, the compiler automatically applies |
@PaulRBerg via-ir is not enabled by default yet. You can expect it to be default in an upcoming breaking release. The easiest way to test would be in Foundry, by adding |
Good to know!
This doesn't clear up the mystery yet of why the code snippets all yield the same gas cost even if |
It's likely because it uses different opcodes. See https://godbolt.org/z/q8K4WGqzr |
Thank you ser, will take a look. |
Alleged Gas Costs
At the time of opening the issue, the Optimal Comparison Operator document makes the following claim:
And then, the following gas costs are provided:
Actual Gas Costs
In the first example below, each function execution will consume exactly 21,162 gas (with the function
compare
per se consuming exactly 98 gas).Try these on Remix with the optimizer enabled and set to 200 runs
1. Require example
2. If/ else example
And in this case, the reported
gasUsed
will be 7.Possible Explanations
Let's start with this is what definitely isn't - this is not a matter of enabling the optimizer. Even with the optimizer disabled, the
> 0
and!= 0
checks cost the same in Solidity v0.8.17. That leaves with a couple of options left:Whatever the case, as discussed in #3 and #15, the best way to avoid situations like this in the future would be to document the methodology that you used to obtain the reported gas costs, so that others can repeat your process and catch mistakes more easily.
The text was updated successfully, but these errors were encountered: