0

I read in many places that view functions do not cost gas however that's not true because they cost gas for blockchain operations even if those do not change the state. Correct me if I am wrong For example:

pragma solidity ^0.4.17;

contract myContract {
    uint[] public anArray;   /// assume it has 1,000,000 (1Million) elements

/* function which returns how many times a specific element is in the n array*/

    function elementIndex(uint element) public view returns(uint){
        uint counter;
        for(uint i; i<anArray.length; i++){
            if(anArray[i] == element){
                counter++;
            }
        }
        return counter;
    }
function returnAllElements() public view returns(uint[]){
return anArray;
}}

The real problem comes on the front end when the array has 1 million elements. Running elementIndex() will never work because the iteration will take too long. returnAllElements will not work either (I assume).

What can be done in such circumstances?

1

In your case, both elementIndex and returnAllElements functions will cost no gas as both the functions are reading state variables from the blockchain and give an intended result.

You can optimize the above functions to reduce a time taken by them.

Refer the following question to understand View/Pure Gas usage - Cost gas if called internally by another function?

Refer the following blog to understand the difference between calls and transactions in ethereum -

https://blog.b9lab.com/calls-vs-transactions-in-ethereum-smart-contracts-62d6b17d0bc2

2

View will not cost gas only if called from outside the network, that is if a function in a contract is view and is called from another contract it will cost gas.

The reason it will not cost gas if called from outside the network is that the function can be resolved in the local node that you are using to connect to the network without submitting a transaction.

Hope this helps.

  • view only costs gas when called from normal (state changing) function, no? I don't think it matters if you call view from other contract as long as the function in other contract is also view. Or i'm wrong? – Maxpeinas Sep 25 '18 at 11:08

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.