Gas(Execution costs) - Add Entity operation:
Simple Array : 89124
Simple Mapping : 66897
Result: Simple Array add entity operation consumes 28.49% more gas than the simple mapping add entity operation. There is noticeable difference. This is possibly due to the nature of the push operation in which the element is inserted at the last of array. The mapping add entity is a direct insert of a struct into the key (address) and thus consuming less gas.
Gas(Execution costs) - Update Entity operation:
Simple Array : 43566
Simple Mapping : 27490
Result: Simple Array Update entity operation consumes 45.25% more than the simple mapping update entity operation. The difference is significant. This is because the array elements have to be iterated and condition checked to confirm the address intended for update. The mapping update entity is a direct update of a entity value for the given key (address) and thus consuming less gas.
simpleArray.sol
pragma solidity 0.8.0;
contract simpleArray {
struct EntityStruct {
uint entityData;
address _entityAddress;
}
EntityStruct[] public entityStructs;
function addEntity(uint _data, address _address) public returns(bool success) {
EntityStruct memory newEntity;
newEntity.entityData = _data;
newEntity._entityAddress = _address;
entityStructs.push(newEntity);
return true;
}
function updateEntity(uint _data) public returns(bool success) {
for (uint i = 0; i <= entityStructs.length - 1; i++) {
if(entityStructs[i]._entityAddress == msg.sender) {
entityStructs[i].entityData = _data;
}
}
return true;
}
}
simpleMapping.sol
pragma solidity 0.8.0;
contract simpleMapping {
struct EntityStruct {
uint entityData;
address _entityAddress;
}
mapping (address => EntityStruct) public entityStructs;
function addEntity(uint _data, address _address) public returns(bool success) {
entityStructs[_address].entityData = _data;
entityStructs[_address]._entityAddress = _address;
return true;
}
function updateEntity(uint _data, address _address) public returns(bool success) {
entityStructs[_address].entityData = _data;
return true;
}
}