Gas optimization is satisfying. You shave a few thousand gas off a function and feel clever. But some optimizations trade away safety in ways that are not obvious, and I have seen "optimized" contracts that introduced vulnerabilities. Here are the gas wins that are genuinely free, the ones that cost you safety, and how to tell the difference.
Where gas actually goes
Before optimizing, know what is expensive. Storage operations dominate. Writing a fresh storage slot (SSTORE from zero to non-zero) costs a lot; reading storage (SLOAD) is cheaper but still meaningful; computation in memory is cheap by comparison. So the highest-leverage optimizations are about touching storage less.
Free win 1: cache storage reads in memory
If you read the same storage variable multiple times in a function, each read is an SLOAD. Read it once into a local variable instead:







