1

So I am writing a contract on which I have to iterate through array items in order to check customer existence or remove a customer (and so on).

Remix tells me that my actual functions might consume a lot of gas, if that's the case, which is the best way to approach this?

Code:

    function IsUserDone(address user) private view returns(bool){
    for(uint256 i = 0; i < DoneCustomers.length; i++)
    {
        if(DoneCustomers[i] == user)
            return true;
    }
    return false;
}

function IsUserPending(address user) private view returns(bool){
    for(uint256 i = 0; i < PendingCustomers.length; i++)
    {
        if(PendingCustomers[i] == user)
            return true;
    }
    return false;
}

function TransferData(address dude) public {
    require(msg.sender == owner);
    require(IsUserPending(dude));

    for(uint256 i = 0; i < PendingCustomers.length; i++)
    {
        if(PendingCustomers[i] == dude){
            delete PendingCustomers[i];
            owner.transfer(total_price);
            AddDoneCustomers(dude);
        }
    }
}

2 Answers 2

0

You could try solidity inline assembly. It's not always more efficient, but in certain conditions it might save some gas, though it requires more knowledge of EVM.

1
  • hello, I actually used mappings as a wrapper, if toBytes(Customers[address].sender).length == 0 then it's not initialized therefore it's not present in the collection, if it is then I can easily access it with indexing. btw "toBytes(address)" is a function I found here which converts the given address to bytes Commented Jul 23, 2018 at 19:23
0

In addition to storing that data in an array (which requires iterating over to find an item buried at the end of it), storing a mapping of items allows for a faster lookup, though requires more gas on initial creation since you're storing one more item to the blockchain:

mapping (address => bool) private pending

function isUserPending(address user) private view returns(bool) {
  return pending[user];
}
1
  • That's what I did as a workaround, thanks a lot anyways =] Commented Jul 24, 2018 at 20:42

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.