[Ethereum] Gas for view functions

gasgas-limitsolidityview

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?

Best Answer

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