3

I currently have the following loop (some stuff left out)

mapping (address => uint) pendingWithdrawals;

function example () private{
    address[] tempList = List;
    for(uint k = 0; k < tempList.length; k++){
            Struct storage val = mapping[tempList[k]];
            pendingWithdrawals[tempList[k]] = (val.value);
    }
}

In this situation, I am looping over a list which I created locally to save on gas and calling the mapping pendingWithdrawals within the loop. But how can I achieve the same goal with the mapping? Since you can't assign to mappings I can't create a local mapping, write to the local mapping and update the new global mapping once finished. Which makes this for loop very costly in terms of having to call the storage over every iteration within the loop.

  • 1
    Could you provide a working code snippet so we can help you more? What is this 'List' variable, is it passed as a parameter or is it a contract storage variable? And the line "Struct storage val = mapping[tempList[k]];" does not make it clear of what is your exact case. – Muhammad Altabba Feb 21 '18 at 14:21
0

In my opinion, even if you could create a local mapping, put 10 values in it, then update the state variable once, you'd have to pay for 10 storage slots, because the mapping contains 10 values.

  • Is there any way to reduce the cost of this method? Or is this just what's available at this point in the solidity language? – Gabe Feb 21 '18 at 14:08
  • Maybe there is a way to pack the integers into uint128 somehow. – medvedev1088 Feb 21 '18 at 15:14
  • Sorry I meant use uint128 instead of uint and pack them into a single storage slot. – medvedev1088 Feb 21 '18 at 16:37
  • I don't believe that'll work with mappings though. The slot in storage of a mapping value is actually keccak256(k . p), where k is the key and p is the slot index of the root of the mapping. This would make it very hard to compact multiple values into one slot given the fact that they'd have separate keys and thus different locations in storage. – flygoing Feb 21 '18 at 18:28
  • If you were expecting a lot of writes, then savings could be made by having the values stored in an array and have the mapping key->value point to the index in the array of the key. The items in the array can then be uint128 or uint64 and packed into slots. Obviously this is more expensive initially, but if a lot of writes are expected, then it can be a large gas saving. – flygoing Feb 21 '18 at 18:32

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.