Solidity – Returning an Uint Array with Gas and Cost Efficiency Solutions

arraysgassolidity

I have a growing public array

struct MatchInfo {
    uint256 matchId;  
    bool isMatchDone; 
}

MatchInfo[] public matchInfo;

and I want to return an array of uint256 which will loop through matchInfo and find where isMatchdone == false

function getUnfinishedMatches() public constant returns (uint256[]) {
  uint256[] memory unFinishedMatches = new uint[](getMatchCount());

  for (uint i = 0; i <= matchInfo.length; i++) {
    if (matchInfo.isMatchdone == false) {
      unFinishedMatches[i] = matchInfo.matchId;
    }
  }

  return unFinishedMatches;
}

I saw somewhere in the post that constant returns will not use up gas. Is it true? if it is not true, is the above function a bad way of approach/practice to return an array in solidity? If so, what are the alternatives?

Best Answer

It really depends. There are two ways of calling functions from a smart contract

  1. Call them from an Ethereum transaction. This will call the function on-chain and cost you gas from the execution.

  2. Call them read-only without creating a transaction. This costs no gas. This can be done because, since it's a constant function and doesn't modify the state, it can be called without creating an on-chain transaction. This wont work for functions that modify the state because the state wont persist since there is no transaction. This is usually done in web3 by doing call() on the function.

Related Topic