Altszn.com
  • Home
  • Crypto
    • Altcoins
    • Bitcoin
    • Ethereum
    • Monero
    • XRP
    • Zcash
  • Web3
  • DeFi
  • NFTs
No Result
View All Result
Altszn.com
  • Home
  • Crypto
    • Altcoins
    • Bitcoin
    • Ethereum
    • Monero
    • XRP
    • Zcash
  • Web3
  • DeFi
  • NFTs
No Result
View All Result
Altszn.com
No Result
View All Result

Optimizing Gas Costs in Solidity Smart Contracts: Best Storage Practices

Altszn.com by Altszn.com
July 15, 2024
in Web3
0
Optimizing Gas Costs in Solidity Smart Contracts: Best Storage Practices
399
SHARES
2.3k
VIEWS
Share on FacebookShare on Twitter


In recent years, Ethereum Virtual Machine (EVM) networks have gained significant traction. Every day, a growing number of new users join these networks, engaging in numerous transactions. However, this increased activity leads to rising transaction fees, sparking interest in reducing these fees to make Web3 apps more affordable and user-friendly.

One promising solution is optimizing the gas execution of smart contracts. By using the right implementation approach, developers can create more efficient smart contracts, thereby reducing gas fees. This optimization not only makes transactions cheaper but also enhances the overall user experience on EVM networks. As these improvements continue, the future of Web3 applications looks increasingly promising.

Solidity Development

Solidity is the most widely used programming language for developing smart contracts on Ethereum Virtual Machine (EVM) chains. Smart contracts are executed on-chain, and each action in a contract transaction incurs a gas cost. Naturally, complex or resource-intensive operations consume more gas.

The most gas-intensive operations are those related to storage. Adding and reading data from storage can become prohibitively expensive if not handled properly, utilizing all available storage areas. When examining EVM Codes, it is evident that STORE opcodes for storage are significantly more expensive than opcodes for memory usage. Specifically, they are 33 times more costly.

 

Opcode

Gas

Description

SLOAD

100

Load word from storage

SSTORE

100

Save word to storage

MSTORE

3

Load word from memory

MLOAD

3

Save word to memory

Storage Areas 

The EVM offers five storage areas: storage, memory, calldata, stack, and logs. In Solidity, code primarily interacts with the first three because it doesn’t have direct access to the stack. The stack is where EVM processing takes place, and accessing it requires low-level programming techniques. Logs are used by Solidity for events, but contracts cannot access log data once it is created.

Storage

  • A key-value store that maps 256-bit words to 256-bit words;
  • Stores all smart contract’s state variables which are mutable (constants are part of the contract bytecode);
  • Is defined per contract at deployment time.

Memory

Calldata

  • A temporary location which stores function arguments;
  • It can’t be written and is used only for readings.

Gas Optimization Approaches

To lower gas costs related to storage, prioritize using memory over storage. Consider the following smart contract which uses the storage area exclusively:

 
contract GasCostComparison { uint256[] private s_numbers; uint256 private s_sum; function numberSum()public returns(uint256) { for(uint i=0; i< s_numbers.length; i++){ s_sum+=s_numbers[i]; } return s_sum; } function initNumbers(uint256 n)public { for(uint i=0; i < n; i++){ s_numbers.push(i); } } }

If s_numbers is initialized by calling initNumbers with n=10, the gas usage for numberSum would be 53,010 gas.

Avoid Reading Too Often from Storage

In the `for` statement, we compare the index i with s_numbers.length. Even though we might think the array length is read from storage only once, it is read every time the comparison takes place. To optimize, read the length only once from storage:


function numberSum()public returns(uint256) { uint256 l = s_numbers.length; for(uint i=0; i< l; i++){ s_sum+=s_numbers[i]; } return s_sum; }

We store the length read from the storage in the l variable which is stored in the memory area of the new numberSum() function. 

This reduces gas usage to 51,945 gas, saving 1,065 gas.

Avoid Writing Too Often in Storage

Similarly, storing the final sum only at the end of the for statement in the s_sum state variable (which is in storage) is more efficient. Create a temporary variable sum in memory:


function numberSum()public view returns(uint256) { uint256 l = s_numbers.length; uint256 sum = 0; for(uint i=0; i< l; i++){ sum+=s_numbers[i]; } return sum; }

Gas execution this time is 27,770 gas, almost half of the previous cases.

Choosing the right storage type can significantly reduce blockchain gas fees, as shown in the examples above. Optimizing how data is stored and accessed is crucial for minimizing costs and improving the efficiency of smart contracts on Ethereum Virtual Machine (EVM) chains.

By prioritizing memory over storage for mutable data and understanding the nuances of gas costs associated with different operations, developers can significantly enhance the performance and cost-effectiveness of their applications in the Web3 ecosystem.

Solidity Documentation





Read More: blog.web3labs.com

Tags: ContractsCostsGasOptimizingpracticesSmartSolidityStorageweb 3.0Web3
ADVERTISEMENT

Recent

Polygon co-founder steps down, says he can no longer give his best

Polygon co-founder steps down, says he can no longer give his best

May 24, 2025
Crypto, NFTs are a lifeboat in the sinking fiat system: Finance Redefined

Crypto, NFTs are a lifeboat in the sinking fiat system: Finance Redefined

May 23, 2025
'Major Wake-Up Call': How $400M Coinbase Breach Exposes Crypto's Dark Side

'Major Wake-Up Call': How $400M Coinbase Breach Exposes Crypto's Dark Side

May 23, 2025

Categories

  • Bitcoin (4,677)
  • Blockchain (11,077)
  • Crypto (9,015)
  • Dark Web (493)
  • DeFi (8,234)
  • Ethereum (4,716)
  • Metaverse (7,147)
  • Monero (268)
  • NFT (1,276)
  • Solana (4,971)
  • Web3 (20,248)
  • Zcash (479)

Category

Select Category

    Advertise

    Advertise your site, company or product to millions of web3, NFT and cryptocurrency enthusiasts. Learn more

    Useful Links

    Advertise
    DMCA
    Contact Us
    Privacy Policy
    Shipping & Returns
    Terms of Use

    Resources

    Exchanges
    Changelly
    Web3 Jobs

    Recent News

    Polygon co-founder steps down, says he can no longer give his best

    Polygon co-founder steps down, says he can no longer give his best

    May 24, 2025
    Crypto, NFTs are a lifeboat in the sinking fiat system: Finance Redefined

    Crypto, NFTs are a lifeboat in the sinking fiat system: Finance Redefined

    May 23, 2025

    © 2022 Altszn.com. All Rights Reserved.

    No Result
    View All Result
    • Home
      • Home – Layout 1
      • Home – Layout 2
      • Home – Layout 3

    © Altszn.com. All Rights Reserved.

    • bitcoinBitcoin (BTC) $ 108,875.00
    • ethereumEthereum (ETH) $ 2,553.35
    • tetherTether (USDT) $ 1.00
    • xrpXRP (XRP) $ 2.35
    • bnbBNB (BNB) $ 673.68
    • solanaSolana (SOL) $ 176.36
    • usd-coinUSDC (USDC) $ 0.999774
    • dogecoinDogecoin (DOGE) $ 0.227802
    • cardanoCardano (ADA) $ 0.758623
    • tronTRON (TRX) $ 0.271688
    • staked-etherLido Staked Ether (STETH) $ 2,552.51
    • wrapped-bitcoinWrapped Bitcoin (WBTC) $ 108,603.00
    • suiSui (SUI) $ 3.64
    • hyperliquidHyperliquid (HYPE) $ 34.17
    • wrapped-stethWrapped stETH (WSTETH) $ 3,068.06
    • chainlinkChainlink (LINK) $ 15.67
    • avalanche-2Avalanche (AVAX) $ 23.08
    • stellarStellar (XLM) $ 0.288557
    • shiba-inuShiba Inu (SHIB) $ 0.000014
    • bitcoin-cashBitcoin Cash (BCH) $ 427.42
    • leo-tokenLEO Token (LEO) $ 8.82
    • hedera-hashgraphHedera (HBAR) $ 0.190127
    • the-open-networkToncoin (TON) $ 3.01
    • litecoinLitecoin (LTC) $ 96.66
    • moneroMonero (XMR) $ 395.66
    • wethWETH (WETH) $ 2,557.32
    • polkadotPolkadot (DOT) $ 4.58
    • usdsUSDS (USDS) $ 0.999825
    • bitget-tokenBitget Token (BGB) $ 5.61
    • wrapped-eethWrapped eETH (WEETH) $ 2,724.24
    • binance-bridged-usdt-bnb-smart-chainBinance Bridged USDT (BNB Smart Chain) (BSC-USD) $ 0.999413
    • pepePepe (PEPE) $ 0.000014
    • pi-networkPi Network (PI) $ 0.768599
    • ethena-usdeEthena USDe (USDE) $ 1.00
    • whitebitWhiteBIT Coin (WBT) $ 31.88
    • coinbase-wrapped-btcCoinbase Wrapped BTC (CBBTC) $ 108,879.00
    • aaveAave (AAVE) $ 266.25
    • bittensorBittensor (TAO) $ 433.81
    • uniswapUniswap (UNI) $ 6.17
    • daiDai (DAI) $ 1.00
    • nearNEAR Protocol (NEAR) $ 2.81
    • aptosAptos (APT) $ 5.39
    • jito-staked-solJito Staked SOL (JITOSOL) $ 212.50
    • okbOKB (OKB) $ 52.40
    • ondo-financeOndo (ONDO) $ 0.955184
    • blackrock-usd-institutional-digital-liquidity-fundBlackRock USD Institutional Digital Liquidity Fund (BUIDL) $ 1.00
    • kaspaKaspa (KAS) $ 0.109988
    • crypto-com-chainCronos (CRO) $ 0.096252
    • ethereum-classicEthereum Classic (ETC) $ 18.60
    • internet-computerInternet Computer (ICP) $ 5.30
    • bitcoinBitcoin (BTC) $ 108,875.00
    • ethereumEthereum (ETH) $ 2,553.35
    • tetherTether (USDT) $ 1.00
    • xrpXRP (XRP) $ 2.35
    • bnbBNB (BNB) $ 673.68
    • solanaSolana (SOL) $ 176.36
    • usd-coinUSDC (USDC) $ 0.999774
    • dogecoinDogecoin (DOGE) $ 0.227802
    • cardanoCardano (ADA) $ 0.758623
    • tronTRON (TRX) $ 0.271688
    • staked-etherLido Staked Ether (STETH) $ 2,552.51
    • wrapped-bitcoinWrapped Bitcoin (WBTC) $ 108,603.00
    • suiSui (SUI) $ 3.64
    • hyperliquidHyperliquid (HYPE) $ 34.17
    • wrapped-stethWrapped stETH (WSTETH) $ 3,068.06
    • chainlinkChainlink (LINK) $ 15.67
    • avalanche-2Avalanche (AVAX) $ 23.08
    • stellarStellar (XLM) $ 0.288557
    • shiba-inuShiba Inu (SHIB) $ 0.000014
    • bitcoin-cashBitcoin Cash (BCH) $ 427.42
    • leo-tokenLEO Token (LEO) $ 8.82
    • hedera-hashgraphHedera (HBAR) $ 0.190127
    • the-open-networkToncoin (TON) $ 3.01
    • litecoinLitecoin (LTC) $ 96.66
    • moneroMonero (XMR) $ 395.66
    • wethWETH (WETH) $ 2,557.32
    • polkadotPolkadot (DOT) $ 4.58
    • usdsUSDS (USDS) $ 0.999825
    • bitget-tokenBitget Token (BGB) $ 5.61
    • wrapped-eethWrapped eETH (WEETH) $ 2,724.24
    • binance-bridged-usdt-bnb-smart-chainBinance Bridged USDT (BNB Smart Chain) (BSC-USD) $ 0.999413
    • pepePepe (PEPE) $ 0.000014
    • pi-networkPi Network (PI) $ 0.768599
    • ethena-usdeEthena USDe (USDE) $ 1.00
    • whitebitWhiteBIT Coin (WBT) $ 31.88
    • coinbase-wrapped-btcCoinbase Wrapped BTC (CBBTC) $ 108,879.00
    • aaveAave (AAVE) $ 266.25
    • bittensorBittensor (TAO) $ 433.81
    • uniswapUniswap (UNI) $ 6.17
    • daiDai (DAI) $ 1.00
    • nearNEAR Protocol (NEAR) $ 2.81
    • aptosAptos (APT) $ 5.39
    • jito-staked-solJito Staked SOL (JITOSOL) $ 212.50
    • okbOKB (OKB) $ 52.40
    • ondo-financeOndo (ONDO) $ 0.955184
    • blackrock-usd-institutional-digital-liquidity-fundBlackRock USD Institutional Digital Liquidity Fund (BUIDL) $ 1.00
    • kaspaKaspa (KAS) $ 0.109988
    • crypto-com-chainCronos (CRO) $ 0.096252
    • ethereum-classicEthereum Classic (ETC) $ 18.60
    • internet-computerInternet Computer (ICP) $ 5.30