Skip to content

Instantly share code, notes, and snippets.

@encody
Last active December 3, 2021 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save encody/ac0bce6c2c3c59ab979de2b179ae1e55 to your computer and use it in GitHub Desktop.
Save encody/ac0bce6c2c3c59ab979de2b179ae1e55 to your computer and use it in GitHub Desktop.
storage, memory, calldata comparison in Solidity
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
contract StorageTest {
struct ComplexStruct {
uint256 x;
uint256 y;
}
ComplexStruct public myValue;
function storageByRefOrValueTest () public {
ComplexStruct storage anotherStruct;
// ComplexStruct storage anotherStruct = ComplexStruct({ x:0, y:0 });
anotherStruct = myValue;
anotherStruct.y += 100;
}
function reset () public {
myValue.x = 0;
myValue.y = 0;
}
function setStruct1 (ComplexStruct calldata c) public { // 67799
// copy and increment
myValue = c;
myValue.x = myValue.x + 1;
myValue.y = myValue.y + 1;
}
function setStruct2 (ComplexStruct calldata c) public { // 66352
// increment without copy
myValue.x = c.x + 1;
myValue.y = c.y + 1;
}
function setStruct3 (ComplexStruct memory c) public { // 67430
// copy and increment
myValue = c;
myValue.x = myValue.x + 1;
myValue.y = myValue.y + 1;
}
function setStruct4 (ComplexStruct memory c) public { // 66937
// increment without copy
myValue.x = c.x + 1;
myValue.y = c.y + 1;
}
// function test() public {
// setStruct1(ComplexStruct({x:1,y:2}));
// }
function getStruct () public view returns (ComplexStruct memory) {
return myValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment