Track 4 · Solidity foundations · lesson 3
Types and state variables
9 min
Track 3 said storage is expensive and memory is cheap. Here is what that means with your hands on it.
Nudge
Show me the approach
Show me the code
Explain the solution
The types you will actually use
Solidity has many types. In practice you will spend most of your time with five:
uint256— an unsigned integer, 0 to about 1.2 × 1077. The default choice for amounts, counts, timestamps and IDs.address— a 20-byte account identifier.address payableif you intend to send ETH to it.bool—trueorfalse.stringandbytes— variable length, and noticeably more expensive than the fixed-size types.mapping— key to value, covered in its own lesson.
Use uint256 unless you have a specific reason not to. Smaller types like
uint8 sound cheaper but usually are not: the EVM works in 32-byte words, so a
uint8 gets padded out anyway and can cost more in extra masking
instructions.
The exception is packing several small values into one slot deliberately, which is a real optimisation and a later topic.
Predict
A `uint256` holding 0 is set to 5, then later back to 0. Which write costs the most gas?
Declaring versus assigning
A state variable declared with a value — uint256 public count = 10; — is
written into storage during deployment. That is part of why deploying costs gas
before anyone has called a thing.
A variable declared inside a function lives in memory and vanishes when the call ends. It costs almost nothing, and it cannot remember anything.
Check
Which of these survives after the transaction that set it finishes?
Worth remembering
- Reach for `uint256` by default — smaller integer types are usually not cheaper.
- Writing a fresh storage slot costs ~22,100 gas; overwriting a used one ~5,000; clearing one earns a refund.
- Contract-level variables are storage and persist; variables inside functions are memory and vanish.
- Initialising a state variable costs gas at deployment time.