0

As far as I understand there is no way to automatically reset all values of a mapping to default in solidity. now lets say I have a mapping mapping with 7 keys and values set. to refresh all the values to zero is it better to use a loop or doing it manually like this:

mapping(uint256 => uint256) public Vals;
Vals[1] = Vals[2] = Vals[3] = Vals[4] = Vals[5] = Vals[6] = Vals[7] = 0;

Manually setting all the values to zero or using a for loop to do this? which way is more gas efficient?

1 Answer 1

0

I tested it out and found out that the loop will cost more gas, the one you mentioned costs less gas

    mapping(uint256 => uint256) public Vals;

    function set() external {
        for (uint256 i; i <= 7; ++i) {
            Vals[i] = 2;
        }
    }

    function deleteWithoutLoop() external {
        Vals[1] = Vals[2] = Vals[3] = Vals[4] = Vals[5] = Vals[6] = Vals[7] = 0;
        //transaction cost - 45458
        //execution cost -   35758
    }

    function deleteWithLoop() external {
        for (uint256 i; i <= 7; ++i) {
            Vals[i] = 0;
            //trasaction cost - 50672
            //execution cost -  42275
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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