Created
September 29, 2022 14:34
-
-
Save pcaversaccio/8b7e537012e3c924515bac5f5d2e0e4e to your computer and use it in GitHub Desktop.
Struct writing (memory vs. storage) comparison.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.8.17; | |
contract Storage { | |
struct SomeStruct { | |
uint16 a; | |
uint16 b; | |
uint16 c; | |
uint16 d; | |
} | |
SomeStruct private _s; | |
// gas: 2474 (write to memory, then write to storage) | |
function writeStructMemory(uint16 a, uint16 b, uint16 c, uint16 d) public returns (uint256 gasUsed) { | |
uint256 startGas = gasleft(); | |
SomeStruct memory s = SomeStruct({a: a, b: b, c: c, d: d}); | |
_s = s; | |
gasUsed = startGas - gasleft(); | |
} | |
// gas: 2351 (with storage pointer) | |
function writeStructStorage(uint16 a, uint16 b, uint16 c, uint16 d) public returns (uint256 gasUsed) { | |
uint256 startGas = gasleft(); | |
SomeStruct storage s = _s; | |
s.a = a; | |
s.b = b; | |
s.c = c; | |
s.d = d; | |
gasUsed = startGas - gasleft(); | |
} | |
function readStruct() public view returns (SomeStruct memory) { | |
return _s; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment