Smart contract gas optimization means writing Solidity so each transaction runs fewer expensive operations, mainly storage reads and writes, and deploying on a network where the remaining cost is small. The biggest wins come from storage layout, data location (calldata vs. memory), contract structure and the choice of chain. Done carefully, it lowers what your users pay on every call. Done carelessly, it creates security bugs that cost far more than the gas you saved.
This guide is for founders and product leads in the UAE and GCC who commission Web3 products and want to know what good gas engineering looks like, what to ask for and how it affects budget.
TL;DR
- Storage is the main cost driver. Packing variables, caching reads and avoiding unnecessary writes usually matter more than clever syntax.
- Use
calldatafor read-only external inputs,constantandimmutablefor fixed values, and keep inheritance and cross-contract calls lean. - Layer 2 networks cut fees sharply, but on L2 the size of your calldata matters more than on Ethereum mainnet.
- Measure before and after on your exact compiler version and target chain. Never optimize on instinct.
- Never trade security for savings. Inline assembly and aggressive packing need review and an audit.
Table of Contents
- What gas is and why your contract design sets the bill
- Where gas goes: the costs that matter most
- Practical Solidity techniques that save gas
- Choosing the chain: how Layer 2 changes the math
- Measure before and after
- Security comes first: where optimization goes wrong
- What it costs and how long it takes
- How to choose a development partner who treats gas seriously
- Build a gas-efficient contract with us
- FAQ
- Sources
What gas is and why your contract design sets the bill
Gas is the unit that measures computational effort on the Ethereum Virtual Machine (EVM). The fee a user pays is gas used multiplied by the base fee plus the priority fee. Your code controls the first number. Network demand controls the second.
Researchers describe this as a gas triangle of usage, price and limit: usage depends on the bytecode your contract executes, while price depends partly on how busy the network is. You cannot change the market, but you can change how many operations each user action triggers.
For a business, this turns a technical detail into a product question. If minting, trading or claiming costs too much, users leave, no matter how good the interface is. Gas efficiency belongs in the product requirements, not in a cleanup phase at the end.
Where gas goes: the costs that matter most
Not all operations are equal. Writing to storage dwarfs almost everything else. A zero-to-nonzero storage write costs 22,100 gas in total (20,000 for the write and 2,100 for a cold access), while a nonzero-to-nonzero write costs 5,000 gas. Any design that avoids a fresh storage slot, or avoids rewriting a value that has not changed, saves real money on every call.
Structure also matters. A 2025 academic review notes that deep inheritance hierarchies and excessive cross-contract calls raise gas use and deployment cost through larger bytecode and external call overhead. Keeping a contract focused is both cleaner and cheaper.
Practical Solidity techniques that save gas
The techniques below are the ones we expect to see in any production contract. Each is well documented, and each has a condition under which it helps.
Pack storage variables
The Solidity documentation explains that contiguous items smaller than 32 bytes are packed into one storage slot when possible. Its own example: declaring uint128, uint128, uint256 takes two slots, while uint128, uint256, uint128 takes three. Same data, different order, one extra slot.
The same page adds an important limit. Smaller types only help where the compiler actually packs them, in storage. For function arguments or memory values there is no inherent benefit, because the EVM works on 32 bytes at a time and needs extra operations to shrink values.
Packing has a design cost too. Alchemy's documentation points out that if packed variables are not usually used together, the extra bitwise operations needed to read one value can make access more expensive. Pack fields that are read and written together.
Use calldata for read-only external inputs
When an external function only reads an array or struct argument, declare it calldata. An audit report from Code4rena explains that with memory, the decoding step needs a loop that copies each element, at least 60 gas per iteration, while calldata avoids the loop. A TRON developer guide makes the same point about minimizing copy operations.
Cache repeated reads and combine mappings
If a function reads the same storage variable several times, copy it into a local variable once. The same Code4rena report notes that caching a mapping value in a local variable saves roughly 42 gas per access by skipping the repeated key hash. It also notes that merging several address-to-value mappings into one mapping to a struct can save a storage slot and avoid a 20,000 gas initial write per mapping combined.
Use constants and immutables
Values that never change should not live in regular storage. According to the TRON guide, constant values are embedded in the bytecode at compile time, and immutable values set in the constructor avoid storage retrieval costs when read. Fee percentages, token decimals and fixed addresses are typical candidates.
Tighten visibility and function types
The Conflux documentation recommends marking functions that do not modify state as view or pure, using the most restrictive visibility that works, and reusing computed values instead of recalculating them. It also suggests bytes32 over string for fixed-size text and keeping large data off-chain, for example on IPFS, with only the essentials stored on-chain.
Prefer mappings to loops over arrays
If you can look up data by key, use a mapping instead of traversing an array. The TRON guide notes mappings are generally more efficient than arrays for this case. Unbounded loops are also a reliability risk, because a loop that grows with user count can eventually become too expensive to execute.
Choosing the chain: how Layer 2 changes the math
The most powerful gas decision is often where you deploy. CoinGecko reports that after Ethereum's Dencun upgrade in March 2024, which introduced EIP-4844 blob data, L2 fees fell by over 90%, with average swap costs dropping from about $86 on mainnet to under $0.39 on L2s.
The reason is structural. Research from TRITON describes how L2s once spent 70 to 80% of revenue on L1 settlement, and blobs cut that to a few percent.
L2 does not make optimization irrelevant, though. Security documentation on L2 considerations explains that L2 transactions have two cost components: execution gas and the cost of posting data to L1. For gas-efficient design on L2, calldata size matters more than it does on L1, so compact function arguments pay off there.
When we scope a project, chain choice follows the product: expected transaction volume, user wallet habits, liquidity needs and the ecosystem your partners already use. Our blockchain development work covers that decision together with the contract design.

Measure before and after
Optimization without measurement is guesswork. The academic review above notes that compiler version and EVM configuration significantly affect gas for identical code, so you need to benchmark in the context you will deploy to.
A sound process looks like this:
- Write the clear version first. Get correct behavior and tests before touching gas.
- Capture a baseline. Record gas per function for the realistic paths users take, not just the happy-path demo, and record deployment gas separately.
- Change one thing at a time. Packing, caching and data location each get their own measurement so you know what helped.
- Re-run the full test suite. Every optimization must leave behavior and access control unchanged.
- Re-measure on the target chain and compiler settings. A saving on a local test network is not proof for production.
- Keep a gas report in the repository. Future changes can then be compared against it.
If you publish those benchmarks on your own site, a structured data audit can help search and AI engines read the pages correctly.
Security comes first: where optimization goes wrong
The cheapest contract is worthless if it can be drained. Optimizations should preserve patterns such as reentrancy guards and checks-effects-interactions and favor clarity over brevity.
Inline assembly is the clearest example. It allows fine-tuned savings but bypasses safety mechanisms like overflow protection, so it is highly susceptible to vulnerabilities when implemented incorrectly. For contracts that hold funds or are upgradeable, we treat assembly as a last resort, used only in hot paths where measurement shows a meaningful gain and where an independent reviewer signs off.
The researchers behind the 2025 review recommend an integrated approach that combines empirical measurement, formal guarantees and best-practice patterns. In practice that means optimization happens before the audit, not after it, so the auditors review the code you will actually ship. Our guide to smart contract audits and a pre-audit checklist walks through that preparation, and the Web3 development checklist covers security and optimization together.
Regulation is a separate track from gas. If your token, wallet or platform may fall under VARA (Virtual Assets Regulatory Authority) in Dubai or another UAE regulator, take licensing questions to your legal counsel early. Our article on custodial vs. noncustodial wallets explains how wallet architecture choices connect to that discussion.

What it costs and how long it takes
Buyers in the UAE usually ask about budget first, so here is what we can state. Our smart contract suite with frontend integration starts from $20,000 one-off. Final scope depends on contract complexity, chain, integrations and audit requirements, and we do not publish a price for gas optimization as a separate item.
The practical point is that gas work is cheapest when it is built in from the start. Choosing a storage layout and chain during design costs a few days of planning. Rewriting a deployed, audited contract to fix an expensive layout can mean redeployment, data migration and a second audit.
For timeline, ask any partner for a phased plan: design and chain selection, development with gas benchmarks, testing, audit preparation, and deployment. Our smart contract deployment process guide shows how those phases fit together, and our developer guide to building smart contracts covers the earlier stages.
How to choose a development partner who treats gas seriously
Whether you work with us or not, these are fair questions for any Web3 team:
- Do they set a gas budget per function before coding starts, based on how users will actually use the product?
- Do they benchmark on the compiler version and chain you will deploy to?
- Is optimization separated from security review, with tests proving behavior is unchanged?
- Can they explain the trade-offs of packing, assembly and upgradeability in plain business terms?
- Do they handle delivery end to end, from contract to frontend to deployment support?
Our perspective
Gas is a product decision wearing a technical costume. Every user who hesitates at a fee prompt is a lost conversion, so we plan the gas profile of a contract the way we plan its interface: around what the user needs to do, and how often.
Our fully UAE-based team writes and reviews the work in-house, with no outsourcing, so the engineer who designs the storage layout is in the same conversation as the one who builds the frontend and the one who prepares the audit. That is how we keep optimization from drifting into risky shortcuts. Our work has been supported by Aptos Foundation grants, and we bring the same discipline to Ethereum-compatible chains and to Move-based ones.
We favor tailored solutions over templated packages. A marketplace with heavy minting needs a different design from a staking product with rare, large transactions, and we say so up front.
Amal
Build a gas-efficient contract with us
Proud Lion Studios is a Dubai-based studio that builds Web3, blockchain and smart contract products for startups and enterprises across the UAE and beyond. We design contracts for lean execution, pair them with frontend integration, and prepare them for audit and deployment. Explore our smart contract development service to see how we work.
If you already have a contract and want to know where its gas goes, or you are scoping a new product and need a chain and budget recommendation, you can also message us on WhatsApp at +971 54 757 8282.
FAQ
Does gas optimization reduce my contract's security?
It can if done carelessly. Techniques like storage packing, calldata and constants are standard and safe when tested. Inline assembly removes built-in safeguards such as overflow protection, so it needs expert review and an audit before launch.
Is gas optimization still necessary on Layer 2?
Yes, though the savings are smaller in absolute terms. Fees on L2 are much lower than on mainnet, but L2 transactions still pay for posting data to Ethereum, so compact calldata and efficient storage use still reduce what your users pay.
How do I know my optimization actually worked?
Measure gas per function before and after each change, on the same compiler version and target chain, and rerun your full test suite. Keep the results in a gas report so later changes can be compared against it.
When should gas optimization happen in the project?
During design and development, with a final measurement pass before the audit. Layout and chain decisions are cheap to make early and expensive to change after deployment.
Sources
- EVM: Practical explanation of how gas fee works
- The Gas Triangle and Its Challenges to the Development of Blockchain-Powered Applications
- Solidity Gas Optimization: 80+ Tips and Tricks
- Optimal Gas Consumption in Ethereum Smart Contracts: A Targeted Review
- Layout of State Variables in Storage, Solidity documentation
- What is Smart Contract Storage Layout?
- Code4rena NounsDAO audit report
- Gas Optimization Guide for Smart Contracts, TRON Core Devs
- Gas Optimization, Conflux Documentation
- What Are Layer 2s (L2s)?, CoinGecko
- Ethereum Network Economics Part II, TRITON
- Layer 2 Considerations, DF3NDR Web3 Security Books
- Weasel simplify skill, security patterns
- Inline Assembly Vulnerabilities in Solidity
- Structured data audit
Ready to talk through your contract design, chain choice and budget? Book a free discovery call with our team.

