Is it bad practice to systematically use the memory
keyword for variables declared within a function (other than constructor)?
1 Answer
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.
-
Wrt your code snippet: the 2 arrays you initially declared are on storage by default, since they are arrays, isn't it?– hartmutJun 22, 2018 at 13:52
-
1@hartmut They are in storage because they have been declared inside the contract and not inside a function– JesbusJun 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?– hartmutJun 23, 2018 at 15:51
-