1

I have an external view function which has an iteration loop. If the contract's totalSupply gets bigger, then the iteration time will grow as well. I'm testing on rinkeby right now, but when I launch it on mainnet, and if lots of users gets involved, I'm concerned about the function call hits the block gas limit. So I want to calculate the maximum iteration time of the function, but I have no idea how to do it. Here's my function.

function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
    uint256 tokenCount = balanceOf(_owner);

    if (tokenCount == 0) {
        // Return an empty array
        return new uint256[](0);
    } else {
        uint256[] memory result = new uint256[](tokenCount);
        uint256 totalItems = totalSupply();
        uint256 resultIndex = 0;

        uint256 itemId;

        for (itemId = 1; itemId <= totalItems; itemId++) {
            if (itemIndexToOwner[itemId] == _owner) {
                result[resultIndex] = itemId;
                resultIndex++;
            }
        }

        return result;
    }
}
3
  • A view function doesn't cost any gas, because it is not executed by miner. Commented Dec 19, 2018 at 15:07
  • @goodvibration Even if there's some writings on memory array when iterating the loop? I'm confused little bit.
    – Jung Chun
    Commented Dec 20, 2018 at 3:36
  • 1
    As long as it's not a state variable - no. Commented Dec 20, 2018 at 7:56

0

Your Answer

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

Browse other questions tagged or ask your own question.