Skip to content

Commit

Permalink
Refs #454 -- Added Comprasion Operators to general/build/smart-contra…
Browse files Browse the repository at this point in the history
…cts/gas-optimization (#504)

* update general/conflux-basics/glossary.md, regarding the issue #455

* Update docs/general/conflux-basics/glossary.md

Co-authored-by: darwintree <17946284+darwintree@users.noreply.github.com>

* Update glossary.md

* add Comparison Operators

---------

Co-authored-by: darwintree <17946284+darwintree@users.noreply.github.com>
  • Loading branch information
jackleeio and darwintree authored Apr 3, 2024
1 parent 1e100cb commit c11bbea
Showing 1 changed file with 36 additions and 0 deletions.
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.

0 comments on commit c11bbea

Please sign in to comment.