How to get array data in Solidity without using for loop

How to get array data in Solidity without using for loop

Do you find yourself struggling with the efficiency of reading data from large arrays in smart contracts? Well, fear not my Solidity lovers, because I have a trick!

Reading data from an array in Solidity can be a resource consuming process, especially when dealing with thousands of elements. This can cause requests to be canceled by node, which can cause headaches for developers. However, there is another way to do this - without using a for loop!

In the traditional simple approach, you would use a for loop to retrieve all the data from the array. But this can be inefficient and time-consuming.

traditional way

pragma solidity ^0.8.0;

contract MyContract {
    uint[] private myArray;

    function getAllData() public view returns (uint[] memory) {
        uint[] memory result = new uint[](myArray.length);

        for (uint i = 0; i < myArray.length; i++) {
            result[i] = myArray[i];
        }

        return result;
    }
}

So, how do we retrieve all the data from the array without using a for loop? it's actually really easy.

our way

First, create a structure that contains an array of the data type you want to retrieve. In this example we will use the address:

contract MyContract {
    struct Addresses {
        address[] addresses;
    }
}

Next, declare a private variable instance of the structure.

Addresses private addressVar;

Add data to the array, just push the address directly

function addAddress(address _address) external {
    addressVar.addresses.push(_address);
}

Now here's the trick - to retrieve all the data from the array without using a for loop, just pass the declared struct as the return type of the function and use the memory keyword to specify that it will be stored in memory.

function getAddresses() external view returns (Addresses memory) {
    return addressVar;
}

In the return value you will get a tuple of addresses. No need for for loops! This approach saves gas costs and makes your code more efficient.

contract practice{
    struct Addresses{
        address[] addresses;
    }
    Addresses private addressVar;
    function addAddress(address _address) external{
        addressVar.addresses.push(_address);
    }
    function getAddresses() external view returns(Addresses memory){
        return addressVar;
    }
}

Get more blockchain learning materials through Github!

https://github.com/Manuel-yang/BlockChainSelfLearning

Guess you like

Origin blog.csdn.net/qq_23351293/article/details/130307553