3
struct User {
   bool isActive;
   uint256 userAge;
}

mapping(userId => User) public users;

method 1;

function example(uint256 userId) public {
   User memory user = users[userId];
   
   bool active = user.isActive;
   uint256 age = user.userAge;

   users[userId].isActive = false;
}

method 2;

function example(uint256 userId) public {
   User storage user = users[userId];
   
   bool active = user.isActive;
   uint256 age = user.userAge;

   user.isActive = false;
}

Why method 2 cost less gas even we used storage keyword and get the all values from storage? which one should I use?

3 Answers 3

4

What method 1 does:

  • load full User struct from storage (2 sloads)
  • store User struct in memory (mstore)
  • load user.isActive from memory (mload), store on stack
  • load user.userAge from memory (mload), store on stack

method 2 does:

  • store storage pointer user (stack)
  • load user.isActive (sload), store on stack
  • load user.userAge (sload), store on stack

Storage operations are most costly, then memory, (then calldata), then stack. Method 2 bypasses memory altogether and thus is cheaper.

1
  • It looks like I really need to deep dive into low level stuff, thank you. Commented May 18, 2022 at 5:18
0

The 'storage' is used for contract account (address, hashes, amount) related values that are used for function call and transactions. Most actions here cost you some gas. While 'memory' is use to store values for message calls within the contract. expanding 'memory' also will increase cost. 'Stack' is used for computations and can hold 1024 elements.

0

By default, Storage is a suitable data location for both local and state variables. While, data in Memory doesn't persist, thus suitable for function parameters/arguments and cost lesser gas.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.