DEV Community

Rushank Savant
Rushank Savant

Posted on • Updated on

Using right data location.

Using the right data location while creating contracts can help save gas on transactions.
Data locations in solidity:

  • Storage - used while referencing state variable to introduce change
  • Memory - variable is copied to memory and changing it does not change the state of blockchain.(can be used for function inputs as well as to reference state variable to get data)
  • Calldata - same as memory, but can be used only in function inputs.

How to decide the data location?

(Consider the following contract)

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;

contract dataLocation{

    struct Order{
        string productName;
        address reciever;
        bool status;
    }

    mapping(address => Order) public orderDetails;

    function makeOrder1(string memory _productName) external { // using memory location
        Order storage _order = orderDetails[msg.sender];
        _order.productName = _productName;
        _order.reciever = msg.sender;
    }

    function makeOrder2(string calldata _productName) external { // using calldata location
        Order storage _order = orderDetails[msg.sender];
        _order.productName = _productName;
        _order.reciever = msg.sender;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • In this code example we have used storage while introducing change to blockchain i.e updating state variable (orderDetails).
    Note:- if we used memory data location, the _order would have no significance outside the function scope. (no change in state variable orderDetails)

  • The functions makeOrder1 and makeOrder2 use memory and calldata locations respectively for taking function inputs.
    Note:- both functions are doing the same thing, just data locations are different for storing input.

Execution cost of both the functions:
makeOrder1

Image description

makeOrder2

Image description

The execution cost while using calldata reduced to less than half.
Reason-> While using memory, the input data is copied whereas while using calldata the data is taken as it is. Hence the gas is reduced.
Due to this, we cannot make changes to input if they are stored in calldata location. So if we need to make changes to input, we need to use memory

Top comments (0)