DEV Community

Hritam Shrivatava
Hritam Shrivatava

Posted on

2

Data locations in solidity

In Solidity, variables can be stored in different places based on their scope and the duration of storage. The main storage locations in Solidity are:

  1. Memory:

    • Scope: Temporary data storage during the execution of a function.
    • Duration: Limited to the duration of the function call.
    • Example:
     function add(uint256 a, uint256 b) external pure returns (uint256) {
         // Using memory for temporary variables
         uint256 result = a + b;
         return result;
     }
    
  2. Storage:

    • Scope: Persistent data storage on the Ethereum blockchain.
    • Duration: Persists across function calls and transactions.
    • Example:
     contract StorageExample {
         uint256 public storedData;  // Stored in storage
    
         function set(uint256 newValue) external {
             // Setting value in storage
             storedData = newValue;
         }
    
         function get() external view returns (uint256) {
             // Reading value from storage
             return storedData;
         }
     }
    
  3. Stack:

    • Scope: Temporary storage for small, local variables within a function.
    • Duration: Limited to the function's execution.
    • Example:
     function calculateSum(uint256 a, uint256 b) external pure returns (uint256) {
         // Using stack for temporary variables
         uint256 sum = a + b;
         return sum;
     }
    

Understanding the distinction between these storage locations is crucial for writing efficient and gas-optimized Solidity code. Memory is typically used for temporary variables within functions, storage is used for persistent data on the blockchain, and the stack is reserved for small, short-lived variables within a function's execution.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay