Skip to content

Instantly share code, notes, and snippets.

@asdrubalivan
Created July 18, 2022 21:20
Show Gist options
  • Save asdrubalivan/13cbeb7ea645a98a87538aa50ebab21f to your computer and use it in GitHub Desktop.
Save asdrubalivan/13cbeb7ea645a98a87538aa50ebab21f to your computer and use it in GitHub Desktop.
Difference between the usage of the keyworks `memory` and `storage` for solidity

Description

This gist shows the difference between the usage of the keywords storage and memory in Solidity.

Calls

setValueMemory

Note that by calling setValueMemory then s is not modified at all. So for example, if we initialize the contract, then s.value1 and s.value2 will be 0. If we pass a 1 to this function and then we call the view getStruct, it returns the old struct with the values 0 and 0 unchanged

setValueStorage

By using storage within the call to setValueStorage we repeat the process above mentioned, but when we call the view getStruct instead of getting 0 and 0 for the members of this struct, we get 1 for value1. So it's modified.

Conclusion

You can see that the keyword storage works like a pointer to s here

pragma solidity ^0.8.0;
contract MemoryStorageTest {
struct StorageStruct {
uint256 value1;
uint256 value2;
}
StorageStruct s;
function setValueMemory(uint256 _val) external {
StorageStruct memory a = s;
a.value1 = _val;
}
function setValueStorage(uint256 _val) external {
StorageStruct storage a = s;
a.value1 = _val;
}
function getStruct() external view returns (StorageStruct memory) {
return s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment