Related to the findings in: Solidity bool size in Structs

Why does inserting a Struct cause an increase of 5,000 gas per item in the Struct?

For example:

// A Struct that, when tightly packed, is 256bits.
// In theory, should cost 1 SSTORE (20,000) to insert
//   or 5,000 to modify.
struct Struct4by64 {
    uint64 one;
    uint64 two;
    uint64 three;
    uint64 four;
mapping (uint=>Struct4by64) mapS4by64;
uint index = 1;

// exp gas cost: 47k:
//   - 1k (misc)
//   - 21k (tx)
//   - 5k (to increment index)
//   - 20k (to write 32bytes)
// actual gas cost: 63k
//   - 47k (above)
//   - 5k (modify 32bytes by setting two)
//   - 5k (modify 32bytes by setting three)
//   - 5k (modify 32bytes by setting four)
function insert4by64() public {
    mapS4by64[index++] = Struct4by64({
        one: 1,
        two: 1,
        three: 1,
        four: 1

Shouldn't the compiler pack the items in the Struct to a single 256bit write? Why does it waste 15k more gas by updating the Struct value for each items two, three, and four?

Likewise, I've found that reading structs from storage takes 200 gas per item in the struct. What, exactly, is the point of tightly packing the items? Just to save ONE write on creating the Struct?

This makes no sense to me. I'd be better off by storing a single 256bit uint and managing it myself via & and | bitmasks... but that's what the compiler is for, isn't it?


I don't see any reason not to use a single SSTORE here. I think the developers simply didn't have time to implement it.

Here is the issue on Github for this https://github.com/ethereum/solidity/issues/2908

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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