Skip to content

Instantly share code, notes, and snippets.

@gdebenito
Last active February 26, 2019 14:35
Show Gist options
  • Save gdebenito/174ef8049f375f691507335e7b5ebbbe to your computer and use it in GitHub Desktop.
Save gdebenito/174ef8049f375f691507335e7b5ebbbe to your computer and use it in GitHub Desktop.
Here is an example how data is tightly packed with solidity compiler.
pragma solidity >=0.4.22 <0.6.0;
contract StorageOptimization {
uint16 a;
uint16 b;
uint16 c;
uint16 d;
uint64 e;
uint128 f;
function set(uint16 _a, uint16 _b, uint16 _c, uint16 _d, uint64 _e, uint128 _f)
external {
a = _a;
b = _b;
c = _c;
d = _d;
e = _e;
f = _f;
}
function get() external view returns (uint256){
assembly {
mstore(0x0,sload(0x0))
return(0x0,32)
}
}
}

Storage Optimization Solidity:

If we tightly pack variables in a solidity contract, they are stored in one same slot. We are going to store 6 variables with a total storage of 32 bytes = 256 bits.

Variable a => 16 bits Variable b => 16 bits Variable c => 16 bits Variable d => 16 bits Variable e => 16 bits Variable f => 128 bits

For example, if we set the next values:

set(1,2,3,4,5,6)

the storage is stored with inverse order:

Decimal: 2041694201525630780872482490871948902401
Binary: 
f=> 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000110
e=> 0000000000000000000000000000000000000000000000000000000000000101
d=> 0000000000000100
c=> 0000000000000011
b=> 0000000000000010
a=> 0000000000000001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment