Consider the following Solidity function that copies an array from storage to memory and modifies it. What is the expected gas cost behavior when modifying the storage array directly versus modifying the memory copy?
pragma solidity ^0.8.0; contract GasTest { uint256[] public data; constructor() { data.push(1); data.push(2); data.push(3); } function modifyStorage() public { data[0] = 10; } function modifyMemory() public view returns (uint256[] memory) { uint256[] memory temp = data; temp[0] = 10; return temp; } }
Think about the cost difference between writing to storage and writing to memory in Solidity.
Writing to storage is expensive in Solidity because it changes the blockchain state. Memory operations are cheaper but temporary. So modifying storage costs more gas than modifying memory.
In Solidity, why does packing multiple smaller variables into a single storage slot reduce gas costs?
Think about how storage slots are charged in Solidity.
Each 32-byte storage slot costs gas. Packing smaller variables into one slot reduces the total slots used, saving gas on storage operations.
Look at the following Solidity contract. Which line causes unnecessary gas usage due to inefficient storage access?
pragma solidity ^0.8.0; contract Inefficient { uint256 public count; function increment() public { count = count + 1; count = count + 1; } }
Consider how many times the storage variable is written to.
Each write to a storage variable costs gas. Writing twice separately causes double the gas cost. Combining increments before writing once saves gas.
In Solidity, using 'unchecked' can save gas by skipping overflow checks. Which snippet correctly applies 'unchecked' to increment a storage variable?
Remember the syntax for the 'unchecked' block in Solidity.
'unchecked' is a block statement in Solidity. The correct syntax is 'unchecked { ... }'. Other forms are invalid.
You have a struct with multiple small variables stored in an array. How can you optimize gas usage when updating one field of a struct in storage?
Think about minimizing the number of storage writes.
Reading the struct once into memory, updating fields there, and writing back once reduces multiple expensive storage writes, saving gas.