Solidity Data Location and Usage

Solidity Data Location and Usage

Memory

  • Variables stored in memory are confined to a function's execution.
  • Data can be manipulated.
  • They are used for temporary calculations or operations within that function.
  • Memory variables are not accessible outside the function.
  • Once the function completes, memory variables are cleared.
  • Cheaper to use in terms of gas costs compared to storage variables.

Example

 function memoryVariable(string memory _exampleString) public returns (string memory) {
        _exampleString = "example";  // You can modify memory
        string memory newString = _exampleString;  // You can use memory within a function's logic
        return newString;  // You can return memory
    }        

Call Data

  • Calldata is exclusively used for external contract function parameters.
  • It's a non-modifiable and non-persistent storage for function arguments.
  • Calldata behaves similarly to memory.
  • Variables defined as calldata cannot be modified, ensuring the integrity of the data.
  • Calldata parameters in functions retain their original values and are used internally without alteration, returning a new variable if needed.
  • Cheaper to use in terms of gas costs compared to memory variables.

Example


    function calldataVariable(string calldata _exampleString) external returns (string memory) {
        // cannot modify _exampleString
        // but can return it
        return _exampleString;
    }        

Storage

  • Storage variables are written to the blockchain, making them persistent.
  • They can be accessed from anywhere within the smart contract and potentially outside of it.
  • By default, all global variables are storage variables.
  • Writing to storage incurs gas fees due to blockchain transactions.


Example

contract VotingSystem {
    // Storage variables to store the total number of votes for each candidate
    mapping(string => uint256) private votesReceived;

    // Function to cast a vote for a candidate
    function voteForCandidate(string memory candidate) public {
        // Increment the total number of votes for the candidate
        votesReceived[candidate]++;
    }

    // Function to get the total number of votes for a candidate
    function getTotalVotesForCandidate(string memory candidate) public view returns (uint256) {
        return votesReceived[candidate];
    }
}        


Zeeshan Riaz

Software Engineer | Full Stack Web Developer | MERN Stack

8mo

Very helpful!

Like
Reply
Soufiane MASAD

Founder @Oklever | Blockchain Consulting & Advisory | Web 3.0 Development | Tokenization | NFT | DeFi | Decentralized applications | Digital Marketing

8mo

well explained Mohammad Rizwan 🇵🇸

Like
Reply

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics