10 Gas Optimization Tips for Smart Contracts

Andre Costa
Published on:
Mar 8, 2025
Cryptocurrency
Want to save on Ethereum gas fees? Here's how to write efficient smart contracts that reduce costs and improve performance. Gas optimization is crucial for blockchain developers to lower fees, avoid block limits, and enhance the user experience. Below are 10 practical strategies you can start using today:
Choose the Right Data Types: Use smaller data types and pack variables into storage slots efficiently.
Reduce Loop Complexity: Cache array lengths, break loops early, and use batch processing.
Use Memory vs. Storage Correctly: Minimize expensive storage operations by leveraging memory for intermediate calculations.
Write Better Function Modifiers: Simplify modifiers, cache storage reads, and combine related checks.
Apply Short-Circuit Logic: Order conditions by gas cost and use logical operators that stop evaluating early.
Simplify Math Operations: Use bitwise operations, fixed-point arithmetic, and
unchecked
blocks for cheaper calculations.Group Multiple Transactions: Combine tasks into batches or use multicall patterns to save gas.
Store Data in Events: Log non-essential data in events instead of costly on-chain storage.
Minimize Contract Calls: Cache external values, use internal functions, and optimize architecture to avoid redundant calls.
Use Gas-Saving Patterns: Apply pull-over-push, minimal proxies, bitmaps, and storage packing for further savings.
These techniques can significantly cut gas costs while maintaining functionality and security. Whether you're building NFT minting contracts or DeFi protocols, these strategies will help you scale efficiently.
Optimization Tip | Key Benefit | Example |
---|---|---|
Right Data Types | Reduce storage costs | Pack |
Reduce Loop Complexity | Avoid block gas limits | Cache array length in loops |
Memory vs. Storage | Lower expensive storage reads/writes | Use memory for temporary calculations |
Better Function Modifiers | Simplify logic and save gas | Cache storage variables in modifiers |
Short-Circuit Logic | Evaluate fewer conditions | Order checks by gas cost |
Simplify Math Operations | Reduce expensive math operations | Use bitwise shifts for powers of 2 |
Group Transactions | Minimize overhead of multiple calls | Batch token transfers |
Store Data in Events | Avoid unnecessary on-chain storage | Log transfer history in events |
Minimize Contract Calls | Reduce redundant external calls | Cache external data locally |
Gas-Saving Patterns | Advanced optimizations for efficiency | Use minimal proxies or bitmaps for flags |
Start implementing these tips to make your smart contracts leaner and cheaper to execute. Keep reading for detailed examples and code snippets for each strategy!
Gas Optimization in Solidity: 10 tips

1. Choose the Right Data Types
Picking the appropriate data types is crucial for cutting gas costs, especially when using Solidity's storage slot packing.
While smaller types like uint8
or uint16
might seem like obvious choices to save gas, the Ethereum Virtual Machine (EVM) can pack these smaller types into a single 32-byte storage slot when grouped efficiently. Here's an example to illustrate:
To optimize storage and gas usage, keep these strategies in mind:
Group related variables: Arrange smaller variables together to maximize the use of storage slots.
Use fixed-size arrays: These can be more efficient than dynamic arrays, especially when storing small, consistent data points.
Leverage mappings: For more complex data structures, mappings can be a better choice.
These techniques are especially valuable in contracts that handle high transaction volumes, like token contracts. For instance, optimizing data types in a contract processing millions of transactions can lead to significant gas savings over time. But remember, gas optimization should never come at the expense of security. If your contract requires handling large numbers, don’t compromise by using smaller uint
types, as this could lead to overflow risks or other vulnerabilities.
Up next, we’ll look at how simplifying loops can further reduce gas costs.
2. Reduce Loop Complexity
Loops can quickly eat up gas, especially when dealing with large arrays or nested iterations. Optimizing them is key to cutting down gas costs and avoiding block gas limits.
Here’s how to make your loops more efficient:
Cache Array Length: Store the array length in a local variable to avoid recalculating it in each iteration.
Break Early: Exit the loop as soon as the desired condition is met:
Unchecked Math: Use unchecked blocks to save gas when overflow isn’t a concern:
Batch Processing: Process large datasets in smaller chunks to keep operations manageable:
Always test your loops with realistic data sizes to analyze gas usage effectively. For more advanced tips, check out My Web3 Startup for smart contract optimization insights.
3. Use Memory vs Storage Correctly
Memory operations are far cheaper than storage operations - storage can cost up to 100 times more gas. Let’s break it down with an example:
Best Practices for Efficiency
Cache Storage Variables
By caching storage references in a local variable, you reduce repeated storage access, which saves gas.
Use Memory for Intermediate Calculations
Perform calculations in memory when possible, then update storage once at the end. This minimizes costly storage operations.
Return Memory Arrays Instead of Storage
Returning storage arrays directly is expensive. Instead, copy the data to memory first.
Key Considerations
Always evaluate whether data needs to be persistent. If not, memory is usually the better choice. However, be mindful that copying large datasets to memory still incurs gas costs, so use this approach wisely.
Operation Type | Storage Cost | Memory Cost | Best Use Case |
---|---|---|---|
Read | ~200 | 3 | Frequent reads |
Write | ~5,000 | 3 | Persistent data |
Array Access | ~200 per element | 3 per element | Temporary data |
Array Copy | ~20,000+ | ~100 | One-time processing |
Next, we’ll dive into optimizing function modifiers to save even more gas.
4. Write Better Function Modifiers
Function modifiers can drive up gas costs if not handled properly. Here's how to fine-tune them for better efficiency.
Keep Modifier Logic Simple
Avoid cramming too much logic into modifiers. Instead, shift complex operations into separate functions.
Cache Repeated Storage Reads
Modifiers that repeatedly access the same storage variables waste gas. Cache these values to reduce redundant reads.
Pass Only Essential Parameters
Modifiers with too many parameters increase calldata costs. Stick to what's absolutely necessary.
Combine Related Modifiers
If multiple modifiers perform similar checks, merge them into one to cut down on redundant operations.
Gas Cost Comparison
Implementation | Average Gas Cost | Savings |
---|---|---|
Multiple Modifiers | 15,000 | Baseline |
Combined Modifier | 9,000 | 40% |
Cached Storage Reads | 7,500 | 50% |
Optimized Parameters | 6,000 | 60% |
Consider Using Internal Functions
For complex logic, internal functions can sometimes be a better choice than modifiers. They offer greater flexibility and may use less gas.
Modifiers execute code both before and after the main function body, increasing deployment and call costs. Use them wisely to keep your smart contracts lean and efficient. Up next, we'll look at ways to further optimize smart contract execution.
5. Apply Short-Circuit Logic
Short-circuit logic in Solidity can help cut down gas usage. This method takes advantage of how the logical operators &&
(AND) and ||
(OR) evaluate conditions.
How Short-Circuit Evaluation Works
In Solidity, logical operators evaluate conditions from left to right and stop as soon as the result is clear:
&&
stops as soon as it finds afalse
.||
stops as soon as it finds atrue
.
Arrange Conditions by Gas Cost
Order your conditions based on their gas usage, starting with the cheapest.
Gas Cost Breakdown
Implementation | Best Case | Worst Case |
---|---|---|
Without Short-Circuit | 7,900 gas | 7,900 gas |
With Short-Circuit | 800 gas | 7,900 gas |
Optimized Ordering | 800 gas | 7,900 gas |
Use Custom Errors for Efficiency
Custom errors provide a more gas-efficient way to handle failed conditions.
Managing Complex Conditions
When dealing with multiple checks, group related conditions for clarity and efficiency:
6. Simplify Math Operations
Gas optimization in smart contracts often comes down to refining math operations. Complex calculations can consume more gas, so opting for simpler methods can help save costs while maintaining the desired functionality.
Use Bitwise Operations
Bitwise operations are an efficient alternative to division and multiplication by powers of 2. Here's how you can replace them:
Optimize Power Calculations
Exponentiation can be expensive in terms of gas. Replace it with direct multiplication when possible:
Switch to Fixed-Point Arithmetic
When working with decimals, fixed-point arithmetic is a better choice than floating-point operations. It ensures accuracy while keeping gas usage in check:
Reduce Precision Where Possible
Avoid using higher precision than needed. This can simplify calculations and reduce gas costs:
Group Calculations Together
Instead of updating state multiple times, batch calculations can reduce the number of state changes, saving gas:
Leverage Unchecked Math
For Solidity 0.8.0 and newer, you can use unchecked
blocks to skip overflow checks when they aren't necessary. This can further reduce gas usage:
Using unchecked math is particularly useful when you're confident that overflow isn't possible, ensuring both safety and efficiency.
7. Group Multiple Transactions
Combining multiple operations into a single transaction is a practical way to save on gas costs. By reducing the overhead of executing separate transactions, smart contracts can operate more efficiently.
Batch Processing
Batch processing allows you to handle multiple tasks in one go. Here's an example of optimizing token transfers:
By processing multiple transfers in one transaction, you minimize redundant operations and reduce gas usage.
Multicall Implementation
A multicall approach combines independent calls into one, further cutting costs. Here's how it works:
This approach is useful for executing multiple independent contract calls in a single transaction.
State Updates Optimization
When updating multiple state variables, consolidating them into one operation can save gas:
This method avoids multiple state write operations, which are typically expensive.
Bulk Data Processing
Handling large sets of data in one transaction is another way to optimize gas usage. Here's an example:
This approach ensures that all allocations are processed together, saving both time and gas.
Memory Management
Efficient memory allocation is key when working with large datasets. Pre-allocating arrays can help avoid unnecessary resizing, which consumes extra gas:
By managing memory effectively, you can further optimize your batch operations.
For more insights and tailored blockchain solutions, check out My Web3 Startup – Web3, Blockchain, Crypto Design & Development Services.
8. Store Data in Events
To reduce gas costs, consider storing non-essential data in events rather than using on-chain storage. Events provide an efficient way to log data off-chain, making transactions cheaper while still keeping the information accessible. This method works well alongside other gas-saving strategies by shifting data logging away from costly storage.
Why Use Events for Data Storage?
Events are stored in transaction logs instead of contract storage, which makes them much more efficient. Here's an example of how to implement this approach:
Indexed Parameters for Better Efficiency
You can make event logging even more efficient by indexing up to three parameters per event. Indexed parameters allow for quicker filtering and searching.
Using Events for Historical Data
For data that doesn’t affect on-chain logic but needs to be logged, events offer a lightweight alternative to storage:
Tips for Optimizing Events
To save even more gas, keep these strategies in mind when designing events:
Use
bytes32
instead ofstring
for fixed-length data.Limit indexed parameters to the most critical fields for searching.
Group related data into a single event instead of emitting multiple events.
Accessing Event Data
Event data can be retrieved using Web3 libraries or blockchain explorers. Off-chain services can index and query this data efficiently. Here’s an example using Web3.js:
Keep in mind that event data is only available off-chain, so it’s not suitable for logic that needs to run directly on the blockchain.
9. Minimize Contract Calls
Reducing external contract calls can significantly lower gas fees by cutting down on extra computation and state changes. Let's explore some practical strategies, including batch operations, caching, and optimizing contract architecture.
Batch Operations
Combining multiple operations into a single transaction helps reduce gas costs by minimizing overhead. Here's an example:
By grouping related transfers, the batch method reduces the number of transactions and associated gas fees.
Multi-Call Patterns
As mentioned earlier (see section 7), multi-call patterns allow you to execute multiple operations in a single transaction, cutting down on repeated overhead.
Cache External Values
Instead of repeatedly calling external contracts, cache their values when possible. This approach reduces redundant calls and saves gas.
Here, prices are fetched once and stored locally, avoiding multiple external calls.
Internal vs. External Function Calls
Internal function calls are cheaper since they compile to simple EVM jumps, unlike external calls that involve more computation.
Whenever possible, use internal calls for operations that don't require external access.
Contract Architecture Optimization
Organize your contracts to group related functionalities and reduce unnecessary external interactions. For instance:
This structure consolidates user data updates, minimizing external calls and simplifying the contract's logic.
10. Use Gas-Saving Patterns
Leverage proven gas-saving design patterns to make your smart contracts more efficient. Building on earlier optimization techniques, these patterns help fine-tune your contract design for lower gas costs.
Pull-Over-Push Pattern
This pattern changes how value transfers are handled. By shifting the responsibility to the recipient, you can lower gas costs and reduce risks.
Minimal Proxy Pattern
Also called EIP-1167, this pattern allows you to create lightweight contract clones that share logic with a master contract. This approach can cut deployment costs by up to 85%.
Bitmap Pattern
Bitmaps are a great way to store multiple boolean states efficiently, especially when dealing with numerous flags.
Uncheck Pattern
If you're performing operations where overflow/underflow checks aren't necessary, using unchecked
blocks can reduce gas usage.
Storage Packing
Efficiently packing variables can optimize storage usage and reduce costs. Here's an example:
Conclusion
Improving gas efficiency in smart contracts is key to building cost-effective and high-performing blockchain applications. By following these 10 gas optimization tips, developers can cut down transaction costs and boost the efficiency of their smart contracts.
Take this example: My Web3 Startup helped Assassin's Creed resolve months of bugs in just five days to create "Smart Collectibles", a million-dollar digital twin NFT platform. This achievement highlights the impact of well-optimized smart contracts.
I can't recommend them enough. The Smart Contract worked perfectly, the pricing was excellent, and their video guide on contract deployment was clear and helpful.
Such examples emphasize the value of expert reviews and ongoing monitoring. Working with experienced smart contract auditors can help identify areas for improvement while ensuring security and functionality remain intact.
Gas optimization isn’t a one-time fix - it’s a continuous process. Regular security tests and performance checks are essential. For instance, My Web3 Startup helped AIPEPE launch a meme token that hit a $100 million market cap.
With over 127 Web3 projects successfully launched, My Web3 Startup specializes in smart contract reviews and optimization to help developers achieve their goals.