2

Is it bad practice to systematically use the memory keyword for variables declared within a function (other than constructor)?

1 Answer 1

2

It's good practice to explicitly use memory or storage to clarify whether a variable contains a pointer to memory or storage.

You should not always use the memory keyword, because it could make your code really inefficient: When you're assigning an array from storage to a memory pointer variable, the entire array will be read from storage and copied into memory.

Here's an example of a situation where you should not use memory:

contract Test
{
    uint256[1000] lotsOfNumbersInStorage;
    uint256[1000] moreNumbersInStorage;
    function calculateSomething(uint256 a) public view returns(uint256)
    {
        uint256[1000] memory theChosenArray;
        if (a > 0) theChosenArray = lotsOfNumbersInStorage;
        else theChosenArray = moreNumbersInStorage;
        return theChosenArray[3] * theChosenArray[a];
    }
}

Those assignments to theChosenArray look innocent, but they will copy the entire array from storage into memory, which will cost at least 200000 gas (200 gas per storage read * 1000 elements). In this case, you should declare theChosenArray as a storage pointer, not a memory pointer.

4
  • Wrt your code snippet: the 2 arrays you initially declared are on storage by default, since they are arrays, isn't it?
    – hartmut
    Jun 22, 2018 at 13:52
  • 1
    @hartmut They are in storage because they have been declared inside the contract and not inside a function
    – Jesbus
    Jun 22, 2018 at 14:24
  • Thx for this precision. Is any variable declared inside a contract, rather than inside a function, BY DEFAULT, in storage?
    – hartmut
    Jun 23, 2018 at 15:51
  • @hartmut Yes, that is correct
    – Jesbus
    Jun 23, 2018 at 15:55

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.