Skip to content
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

Refs #454 -- Added Comprasion Operators to general/build/smart-contracts/gas-optimization #504

Merged
merged 9 commits into from
Apr 3, 2024
36 changes: 36 additions & 0 deletions docs/general/build/smart-contracts/gas-optimization/LessThan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
displayed_sidebar: generalSidebar
---

# Comparison Operators

In the Ethereum Virtual Machine (EVM), the selection of comparison operators influences the efficiency and gas consumption of smart contracts. Opting for `<` (less than) and `>` (greater than) over `≤` (less than or equal to) and `≥` (greater than or equal to) is notably more gas-efficient. This is due to the absence of direct opcode instructions for `≤` and `≥` in the EVM's design, which requires additional operations to achieve these comparisons.

Given that iszero consumes 3 units of gas, utilizing `≤` and `≥` in contracts that frequently perform comparisons can lead to increased gas expenditures.

**DemoCode**

Below are examples of code achieving the same result using `<` and `<=`, respectively.

```solidity
contract CompareLessThan {
// gas: 247
function isSmallerThan(uint256 value) external pure returns (bool) {
return value < 8;
}
}

contract CompareLessThanOrEqual {
// gas: 250
function isSmallerThanOrEqual(uint256 value) external pure returns (bool) {
return value <= 7;
}
}
```

Assuming `value` is 7, both functions will return the same result. However, the `<` operator will be more gas-efficient than the `<=` operator.


Recommendations for gas optimization:

🌟 Using the `<` and `>` operators is more gas-efficient than `<=` and `>=` in smart contracts.