Market Cap: $2.8588T -5.21%
Volume(24h): $157.21B 50.24%
Fear & Greed Index:

38 - Fear

  • Market Cap: $2.8588T -5.21%
  • Volume(24h): $157.21B 50.24%
  • Fear & Greed Index:
  • Market Cap: $2.8588T -5.21%
Cryptos
Topics
Cryptospedia
News
CryptosTopics
Videos
Top Cryptospedia

Select Language

Select Language

Select Currency

Cryptos
Topics
Cryptospedia
News
CryptosTopics
Videos

How to Write a Gas-Efficient Smart Contract in Solidity?

Optimize Solidity gas usage by grouping same-type storage vars, caching array lengths, using unchecked only when safe, reverting with custom errors, and enabling solc’s --via-ir flag.

Jan 26, 2026 at 01:59 pm

Optimize Storage Layout

1. Group variables of the same type together to minimize slot usage.2. Use uint256 instead of smaller types unless packing is intentional.3. Declare state variables in order of decreasing size: uint256, uint128, uint64, uint32, uint16, uint8.4. Avoid using mapping for large datasets if alternatives like arrays with off-chain indexing exist.5. Prefer immutable over constant for values known at deployment time but computed dynamically.

Minimize External Calls and Loops

1. External calls consume significantly more gas than internal function calls; consolidate logic into a single transaction where possible.2. Never iterate over unbounded arrays inside on-chain functions—use event-based pagination or off-chain computation.3. Replace for (uint i = 0; i with fixed-length loops when length is predictable.4. Cache array length in memory before looping: uint len = array.length;5. Avoid nested loops entirely unless both dimensions are strictly bounded and small.

Leverage Assembly for Critical Paths

1. Inline assembly can bypass Solidity’s safety checks and reduce overhead for arithmetic and memory access.2. Use mstore and mload instead of high-level memory assignments where performance is critical.3. Replace keccak256(abi.encodePacked(...)) with keccak256(bytes) when hashing pre-assembled byte sequences.4. Access storage slots directly via sload and sstore only when you’re certain about slot indices and mutability.5. Never use assembly for complex control flow—maintain readability and auditability for core business logic.

Avoid Expensive Operations in Hot Paths

1. Division and modulo operations cost more gas than bit shifting; use x >> n instead of x / 2**n when dividing by powers of two.2. String concatenation with abi.encodePacked is cheaper than string.concat, but both should be avoided in frequently called functions.3. Do not emit events inside loops unless each emission carries unique, necessary data.4. Revert with custom errors instead of string messages: revert InvalidAmount(); saves ~2000 gas per call.5. Use unchecked blocks only when overflow/underflow is mathematically impossible—never in arithmetic involving user input.

Testing and Measurement Practices

1. Measure gas usage using Hardhat’s gasReporter or Foundry’s forge test --gas-report.2. Compare baseline gas costs before and after each optimization to avoid premature micro-optimizations.3. Simulate worst-case scenarios: full arrays, maximum recursion depth, edge-case inputs.4. Profile storage reads/writes separately using EVM trace analysis tools like Tenderly or Blockscout.5. Audit bytecode output with solc --asm to verify compiler optimizations such as constant folding and dead code elimination.

Frequently Asked Questions

Q1. Does using view or pure functions reduce gas consumption?A1. No. These modifiers affect call behavior and state mutability but do not change gas cost during external calls. They only eliminate gas charges when called internally or off-chain.

Q2. Is it safer to use SafeMath in modern Solidity versions?A2. Not required. Solidity 0.8.0+ includes built-in overflow checks. Explicit SafeMath adds unnecessary opcodes and increases deployment gas.

Q3. Can I reduce gas by deploying contracts with stripped bytecode?A3. Yes. Using --via-ir flag with solc enables advanced optimizer passes, often cutting runtime bytecode size by 15–30% and lowering deployment gas significantly.

Q4. Why does emitting an event with indexed parameters cost more gas?A4. Indexed parameters generate topic hashes stored in the log’s topics array, which requires additional SHA3 computations and storage in the log structure—each topic consumes one 32-byte word.

Disclaimer:info@kdj.com

The information provided is not trading advice. kdj.com does not assume any responsibility for any investments made based on the information provided in this article. Cryptocurrencies are highly volatile and it is highly recommended that you invest with caution after thorough research!

If you believe that the content used on this website infringes your copyright, please contact us immediately (info@kdj.com) and we will delete it promptly.

Related knowledge

See all articles

User not found or password invalid

Your input is correct