Memory caching vs direct storage vs pointers
Gas notes
Avoid zero to one storage writes where possible
Reading & Writing #1
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.24;
contract GasCostsV2 {
struct Stream {
// slot 0
uint256 claimed;
// slot 1
uint256 lastClaimedTimestamp;
}
mapping(uint256 tokenId => Stream stream) public streams;
function testMemory() public {
//cache
Stream memory stream = streams[1];
//doStuff
stream.claimed += 10 ether;
stream.lastClaimedTimestamp = block.timestamp;
//update storage
streams[1] = stream;
}
function testStorage() public {
//doStuff
streams[2].claimed += 10 ether;
streams[2].lastClaimedTimestamp = block.timestamp;
}
function testPointers() public {
// pointer
Stream storage stream = streams[3];
//doStuff
stream.claimed += 10 ether;
stream.lastClaimedTimestamp = block.timestamp;
}
}Why does caching to memory cost more than storage?


Links
Reading & Writing #2
Why does caching to memory cost more than storage?
When to cache to memory?
Cache storage variables: write and read storage variables exactly once
Last updated