0

Say I have a struct like this:

struct MyStruct {
    bool foo;
    uint256 bar;
    uint256 baz;
    address qux;
}

If I rewrite it like this:

struct MyStruct {
    bool foo;
    address qux;
    uint256 bar;
    uint256 baz;
}

Would storage become less expensive, since address is an alias for uint160 and bool can only be 0 or 1? What if foo was of type address?

1

Yes, it does for the first case but if foo is an address, no, there are no storage efficiency gains.

If I apply the changes mentioned in the question body, I end up spending a whopping 20,134 less gas for adding a new struct in the mapping.

See transactions on Rinkeby:

The example contract used:

pragma solidity 0.5.11;

contract StorageCostTest {

    struct MyStruct {
        bool foo;
        uint256 bar;
        uint256 baz;
        address qux;
    }

    mapping(uint256 => MyStruct) private myStructs;
    uint256 public nextMyStructId;

    constructor() public {
        nextMyStructId = 1;
    }

    function addItem(bool foo, uint256 bar, uint256 baz, address qux) external {
        myStructs[nextMyStructId] = MyStruct({
           foo: foo,
           bar: bar,
           baz: baz,
           qux: qux
        });
        nextMyStructId += 1;
    }
}

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.