When executing the addEntity function, which design consumes the most gas (execution cost)? Is it a significant difference? Why/why not?
Mapping: 66’058 per Entity | cost all 5 = 330’290
Array: 88’290 after that 71’190 per Entity | cost all 5 = 373’050
The Array Solution is roundabout 13% more expensive for all 5 Operations than the Mapping version.
This is quite alot considering there not beeing a need to do more than save and update.
Add 5 Entities into storage using the addEntity function and 5 different addresses. Then update the data of the fifth address you used. Do this for both contracts and take note of the gas consumption (execution cost). Which solution consumes more gas and why?
Total Cost
Mapping: 592’472
Array: 654’822
Update Cost:
Mapping: 26’7’19
Array: 29’134
Since we only replace the Data in a Entity and do not delete anything the operation is pretty simple, but the Array version is still 9% more Expensive.
I guess its due to the simple Operation producing more Effort within an Array than within a Mapping.
Mapping Contract
pragma solidity 0.8.0;
contract storageDesignMapping {
struct Entity{
uint data;
address _address;
}
mapping (address => Entity) Entities;
function addEntity (uint data) public {
Entities[msg.sender].data = data;
Entities[msg.sender]._address = msg.sender;
}
function updateEntity (uint data) public {
Entities[msg.sender].data = data;
}
}
Array Contract
pragma solidity 0.8.0;
contract storageDesignArray {
struct Entity{
uint data;
address _address;
}
Entity [] public Entities;
//addEntity(). Creates a new entity for msg.sender and adds it to the mapping/array.
function addEntity (uint data) public {
Entity memory addedEntity;
addedEntity.data = data;
addedEntity._address = msg.sender;
Entities.push(addedEntity);
}
//updateEntity(). Updates the data in a saved entity for msg.sender
function updateEntity (uint _index, uint data) public {
Entities[_index].data = data;
}
}