0

I'm struggling to find which way to send data to a struct is cheaper and most efficient. I came up with these 2 different styles:

struct Database
{
   string name;
   string addressPerson; 
}

mapping (string => Database) idToDatabase;

function setPerson(string _id, string _name, string _address) external {
   Database storage person = idToDatabase[_id];
   person.name = _name;
   person.addressPerson = _address;
}  

and

struct Database
{
   string name;
   string addressPerson; 
}

Database[] public people;

mapping (string => uint) idToPerson;

function setPerson(string _id, string _name, string _address) external {
   people.push(Database(_name,_address));
   idToPerson[_id] = people.length-1;           
}

Which should I use and why? I researched a lot and couldn't find an answer. Thank you.

  • 1
    Which one uses less gas? My assumption would be the first, because it writes one less thing to storage. (Writing to storage is so expensive that other minor differences like hashing or storing something temporarily in memory probably don't matter.) But if you're looking for whichever is cheaper, just try them out and see. – smarx Jul 10 '18 at 1:10
0

I tried creating sample contracts with the above two approaches. I used Remix IDE to calculate the costs. Note that these are indicative costs (but still helpful), which could change depending upon many factors.

When you deploy the contract and call the function SetPerson(), it will show you the details of transaction in the bottom pane.

Find out more about difference between Transaction Cost and Execution Cost here

Approach 1 (mapping to object)

  • Contract Deployment

    transaction cost 179161 gas

    execution cost 95141 gas

  • Function call

    transaction cost 65441 gas

    execution cost 41609 gas


Approach 2 (mapping to id, array)

  • Contract Deployment:

    transaction cost 361519 gas

    execution cost 232075 gas

  • Function call

    transaction cost 91228 gas

    execution cost 67396 gas

  • Thank you so much. I'll take a look on the link you sent. As I'm new to Solidity, I have many questions about costs and things related. – Romullo Queiroz Jul 10 '18 at 14:42

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.