Mapping Solution (i commented out the boolean for the sake of the homework)
pragma solidity 0.8.0;
// SPDX-License-Identifier: MIT
contract StoreStructWithMapping{
struct Entity{
uint data;
address _Address;
//bool isKnown;
}
mapping(address => Entity) EntityStruct;
function addEntity( uint _data) public{
//require(EntityStruct[msg.sender].isKnown == false);
EntityStruct[msg.sender].data = _data;
EntityStruct[msg.sender]._Address = msg.sender;
// EntityStruct[msg.sender].isKnown = true;
}
function UpdateEntity( uint _data ) public {
// require(EntityStruct[msg.sender].isKnown == true);
EntityStruct[msg.sender].data = _data;
}
}
Array Solution
pragma solidity 0.8.0;
// SPDX-License-Identifier: MIT
contract ArrayStructAssignment{
struct Entity{
uint _data;
address _address;
}
Entity[] entityStructs;
function addEntity( uint _data) public {
entityStructs.push(Entity(_data, msg.sender));
}
function updateEntity(uint _id ,uint _data) public returns (uint, address) {
//loop through the array to find the index corresponding to the id
for( uint i=0; i<entityStructs.length; i++){
if( _id == i ){
entityStructs[i]._data = _data;
return (entityStructs[i]._data, entityStructs[i]._address);
}
else {
continue;
}
}
}
}
}
The addEntity function using a mapping costs
66786 gas
The addEntity function using an array costs
88190 gas
the array solution consumes around 30% more gas than wih a mapping, considering it a pretty significant increase.
In the mapping solution, upon adding 5 new entities, it costed 333,930 gas, and changing the data of the 5th address costed 29035 gas.
In the array solution, upon adding 5 new entities, it costed 372,550 gas, the first element costing 88190 gas and the elements after costing 71090 gas, and changing the data of the 5th address costed 33551 gas.
The array execution consumes more gas since it has to iterate through the list to find the right index, whereas a map simply uses the inputted key to find the value and doesn’t have to search through a whole list.