From 841b7dc6fe119632bce0544c0fa4bd185751dda3 Mon Sep 17 00:00:00 2001 From: JackLee <280147597@qq.com> Date: Fri, 29 Mar 2024 18:11:07 +0800 Subject: [PATCH] Refs #454 -- Added ShortCircuiting to general/build/smart-contracts/gas-optimization (#493) * 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 short-circuiting in gas-optimization * update shortCircuit --------- Co-authored-by: darwintree <17946284+darwintree@users.noreply.github.com> --- .../gas-optimization/shortCircuit.md | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 docs/general/build/smart-contracts/gas-optimization/shortCircuit.md diff --git a/docs/general/build/smart-contracts/gas-optimization/shortCircuit.md b/docs/general/build/smart-contracts/gas-optimization/shortCircuit.md new file mode 100644 index 0000000000..d3c609feb3 --- /dev/null +++ b/docs/general/build/smart-contracts/gas-optimization/shortCircuit.md @@ -0,0 +1,50 @@ +--- +displayed_sidebar: generalSidebar +--- + +# Short-Circuiting + +In Solidity, where every blockchain-affecting operation requires gas, short-circuiting is a coding technique that evaluates the second argument of a logical operation only if the first doesn't conclusively determine the outcome, thus significantly reducing unnecessary gas consumption and enhancing efficiency. + +**DemoCode** + +Below, we demonstrates how short-circuiting can be applied to minimize gas usage: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.13; + +contract LogicOptimization { + // High gas consumption function + function heavy() public pure returns (bool ok) { + uint num; + for (uint256 i = 0; i < 1000; i++) { + num = i + 1; + } + ok = true; + } + + // Low gas consumption function + function light() public pure returns (bool ok) { + ok = true; + } + + // No short-circuiting: higher gas usage + function basic() external pure { + heavy() || light(); // Evaluates both heavy() and light() + } + + // With short-circuiting: reduced gas usage + function efficient() external pure { + light() || heavy(); // light() evaluated first, heavy() skipped if light() is true + } +} +``` + +Recommendations for gas optimization: + +🌟 Utilize **short-circuiting** to prevent unnecessary function calls or computations. + +🌟 Place functions or conditions likely to succeed (or that are less gas-consuming) **before** others in logical operations. + +🌟 Understand the gas cost of operations and structure your code to minimize these costs whenever possible.