Uniswap / v3-core

🦄 🦄 🦄 Core smart contracts of Uniswap v3
https://uniswap.org
Other
4.38k stars 2.68k forks source link

TickBitmap, SwapMath, Oracle: replace "if (A && B)" to save gas fees #656

Open BurtonQin opened 1 year ago

BurtonQin commented 1 year ago

The solidity compiler generates more code for “if (A && B) {}” than for “if (A) {if (B) {} }”. Our experiment shows that switching from “if (A && B) {}” to “if (A) {if (B) {} }” can save gas fee.

There are six such cases: https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/TickBitmap.sol#L49 https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SwapMath.sol#L87 https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/SwapMath.sol#L91 https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/Oracle.sol#L93 https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/Oracle.sol#L134 https://github.com/Uniswap/v3-core/blob/d8b1c635c275d2a9450bd6a78f3fa2484fef73eb/contracts/libraries/Oracle.sol#L179

Replacing

if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break;

with

if (targetAtOrAfter) {
    if (lte(time, target, atOrAfter.blockTimestamp)) {
         break;
    }
}

can save gas fees and does not hurt readability.