Gas:
Add: 66209 gas
Update: 28893 gas
pragma solidity 0.7.5;
contract StorageAssignment {
struct Entity {
uint data;
address _address;
}
mapping(address => Entity) entities;
function addEntity(uint data) public {
require(!isEntity(msg.sender), "Entity already persisted");
entities[msg.sender] = Entity(data, msg.sender);
}
function isEntity(address _address) private view returns (bool) {
if(entities[_address]._address == _address) {
return true;
}
return false;
}
function updateEntity(uint _data) public {
require(isEntity(msg.sender), "Should addEntity first");
entities[msg.sender].data = _data;
}
}
Gas:
Add: 99008 gas
Update: 59807 gas
pragma solidity 0.7.5;
contract StorageAssignment2 {
struct Entity {
uint data;
address _address;
}
Entity[] entities;
function addEntity(uint data) public {
require(!isEntity(msg.sender), "Entity already persisted");
entities.push(Entity(data, msg.sender));
}
function isEntity(address _address) private view returns (bool) {
for(uint i = 0; i < entities.length; i++) {
if(entities[i]._address == _address) {
return true;
}
}
return false;
}
function updateEntity(uint _data) public {
require(isEntity(msg.sender), "Entity not present");
for(uint i = 0; i < entities.length; i++) {
if(entities[i]._address == msg.sender) {
entities[i].data = _data;
}
}
}
}
Conclusion:
Since my array implementation checks if an address is contained in the array before adding and updating this takes linear time which is more expensive than the mapping lookup.