1

this is my code:

struct Entity{
    address _address;
    uint data;
}

   Entity[] entityArray;

function addEntityArray(uint _data)  public returns(uint){
    entityArray.push(Entity((msg.sender), _data));
    return entityArray[(entityArray.length) - 1].data;
}

to update a struct in this array at any point in time, i will need to keep track of the address and the index of it using MAPPING right? or i have to loop everytime which is costly in gas... how to tackle this issue in the best way possible?

2
  • are you sure you need an array? why not a mapping from address -> data?
    – Majd TL
    Oct 26, 2021 at 7:29
  • I did use the structure you suggested, but for another use case, I need an array to loop through and do some work // or return an array of those objects
    – anthony422
    Oct 26, 2021 at 8:37

1 Answer 1

4

Yes, the easiest way to update a single instance of the array is for every address that invokes addEntityArray() to store the index of the struct.

The mapping would look like this:

mapping(address => uint) public addressesEntityIndex;

Note: it is better to store the index to the struct, not a whole struct because it is cheaper.

The updated function would look like this:

function addEntityArray(uint _data)  public returns(uint){
    Entity storage newEntity = Entity(msg.sender, _data);
    uint entityIndex = entityArray.length;
    entityArray.push(newEntity);
    addressesEntityIndex[msg.sender] = entityIndex;
    return entityArray[entityIndex].data;
}

Note: I slightly modified your function's design, it will cost a bit more gas but it is more human-readable.

And finally, you define a function that will update:

function updateEntityArray(uint _data) public {
    uint addressEntityIndex = addressesEntityIndex[msg.sender];
    entityArray[addressEntityIndex].data = _data
}
9
  • looks good, but when u declared "newEntity" why did u put it in storage? if you make it Entity memory newEntity = Entity(msg.sender, _data); it would be much cheaper
    – anthony422
    Oct 27, 2021 at 6:42
  • 1
    Yes, but if you declared it in memory the moment you addit to the entityArray (entityArray.push(newEntity);) it will be added in the storage and now you have it once in memory and once in storage where as if you declared directly to storage you omit the memory declaration. Oct 27, 2021 at 7:27
  • 1
    ohhh, very true! i forgot about the refference and copy between storage and memory. thanks alot for the answer!
    – anthony422
    Oct 27, 2021 at 14:52
  • you are welcome. dont forget to upvote :) Oct 27, 2021 at 15:00
  • 1
    i did but dont have enough reps :D once i do it'll appear
    – anthony422
    Oct 28, 2021 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.