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;

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.