DEV Community

Cover image for The Hidden Cost of Code: A Senior Dev’s Guide to Gas Optimization in Solidity
Frank Oge
Frank Oge

Posted on

The Hidden Cost of Code: A Senior Dev’s Guide to Gas Optimization in Solidity

In Web2, a slightly inefficient loop costs you a few milliseconds of CPU time. In Web3, that same loop could cost your users $50 in transaction fees.
​Every operation in Solidity costs Gas. As a developer, your job is to write code that is "Gas-Agnostic"—meaning it performs the same task using the least amount of computational effort.
​If you want to move from a Junior to a Senior Solidity Dev, you need to stop thinking about readability and start thinking about OPCODES.
​Here are the three high-impact optimization patterns I use to keep my contracts lean.
​1. Variable Packing (Slot Management)
​Ethereum stores data in 32-byte slots. If you define variables poorly, you waste space.
​The Junior Way:

uint256 a; // Slot 0
bool b; // Slot 1
uint256 c; // Slot 2

This uses 3 full slots.
​The Senior Way:

uint256 a; // Slot 0
uint128 b; // Slot 1
uint128 c; // Slot 1 (Packed!)

By grouping smaller types together, they sit in the same 32-byte slot. This reduces the number of SSTORE (storage write) operations, which are the most expensive things you can do in Solidity.
​2. Calldata vs. Memory
​When passing arrays or strings to a function, you have a choice: memory or calldata.
​memory creates a temporary copy (expensive).
​calldata points directly to the input data (cheap).
​If your function only needs to read the data, always use calldata. It’s a 10% to 20% gas saving for free.
​3. Short-Circuiting and Errors
​Stop using long require strings.
require(balance >= amount, "The user does not have enough balance to complete this transaction");
​Every character in that string costs gas to store and deploy.
​In 2026, we use Custom Errors:

error InsufficientBalance();
if (balance < amount) revert InsufficientBalance();

Custom errors are handled as selectors (4 bytes), making them significantly cheaper than strings.
​The Trade-off
​Gas optimization often makes code harder to read. Use it where it matters: inside loops and in functions that will be called thousands of times. Don't optimize your constructor at the cost of clarity; optimize the functions that your users pay for every day.
​Hi, I'm Frank Oge. I build high-performance software and write about the tech that powers it. If you enjoyed this, check out more of my work at frankoge.com

Top comments (0)